C ++ Unit-Ii
C ++ Unit-Ii
C ++ Unit-Ii
Class
In C++, class is a group of similar objects.
It is a template from which objects are created. It can have fields, methods, constructors etc.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
Output:
201
Sonoo Jaiswal
Output:
201 Sonoo
202 Nakul
C++ Class Example: Store and Display Employee Information
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }
Output:
Let us use a member function to access the members of a previously created class instead of directly
accessing them.
1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void); // Returns dice volume
7. };
Member functions can be defined either within the class definition or separately with the scope resolution
operator,:.
Even if the inline specifier is not used, specifying a member function within the class declaration declares
the function inline. So, you may either define the Volume() function as shown below.
1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void) {
7. return L * B * H;
8. }
9. };
If we want, we may define the identical function outside of the class using the scope resolution operator
(::), as seen below.
1. double Dice::getVolume(void) {
2. return L * B * H;
3. }
The main thing to remember here is that we must use the class name exactly before the :: operator. The dot
operator (.) will be used to perform a member function on an object and will only manipulate data relevant
to that object as follows:
C++ Program:
1. #include <iostream>
2. using namespace std;
3. class Dice {
4. public:
5. double L; // a dice's length
6. double B; // a dice's breadth
7. double H; // a dice's height
8. // Member functions declaration
9. double getVolume(void);
10. void setL(double length);
11. void setB(double breadth);
12. void setH(double height);
13. };
14. // Member functions definitions
15. double Dice::getVolume(void) {
16. return L * B * H;
17. }
18. void Dice::setL(double length)
19. {
20. L = length;
21. }
22. void Dice::setB(double breadth) {
23. B = breadth;
24. }
25. void Dice::setH(double height) {
26. H = height;
27. }
28. // Main function
29. int main() {
30. Dice Dice1; // Declare Dice1 of type Dice
31. Dice Dice2; // Declare Dice2 of type Dice
32. double volume = 0.0; // here the volume of a Dice is stored
33. // dice 1 specification
34. Dice1.setL(6.0);
35. Dice1.setB(7.0);
36. Dice1.setH(5.0);
37. // Dice 2 specification
38. Dice2.setL(12.0);
39. Dice2.setB(13.0);
40. Dice2.setH(10.0);
41. // volume of Dice 1
42. volume = Dice1.getVolume();
43. cout << "Volume of Dice1 : " << volume <<endl;
44. // volume ofDice 2
45. volume = Dice2.getVolume();
46. cout << "Volume of Dice2 : " << volume <<endl;
47. return 0;
48. }
Output:
A static data member is similar to the static member function because the static data can only be accessed
using the static data member or static member function.
And, all the objects of the class share the same copy of the static member to access the static data.
Syntax
The data_type is the variable type in C++, such as int, float, string, etc.
Example 1: Let's create a simple program to access the static data members in the C++ programming
language.
1. #include <iostream>
2. #include <string.h>
3. using namespace std;
4. // create class of the Car
5. class Car
6. {
7. private:
8. int car_id;
9. char car_name[20];
10. int marks;
11.
12. public:
13. // declare a static data member
14. static int static_member;
15. Car()
16. {
17. static_member++;
18. }
19. void inp()
20. {
21. cout << " \n\n Enter the Id of the Car: " << endl;
22. cin >> car_id; // input the id
23. cout << " Enter the name of the Car: " << endl;
24. cin >> car_name;
25. cout << " Number of the Marks (1 - 10): " << endl;
26. cin >> marks;
27. }
28. // display the entered details
29. void disp ()
30. {
31. cout << " \n Id of the Car: " << car_id;
32. cout << "\n Name of the Car: " << car_name;
33. cout << " \n Marks: " << marks;
34. }
35. };
36. // initialized the static data member to 0
37. int Car::static_member = 0;
Output
A static member function shares the single copy of the member function to any number of the class' objects.
We can access the static member function using the class name or class' objects.
If the static member function accesses any non-static data member or non-static member function, it throws
an error.
Syntax
1. class_name::function_name (parameter);
function_name: The function name is the name of the static member function.
parameter: It defines the name of the pass arguments to the static member function.
Example 2: Let's create another program to access the static member function using the class name in the
C++ programming language.
1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7. public:
8. // create static member function
9. static int func ()
10. {
11. return num;
12. }
13. };
14. // initialize the static data member using the class name and the scope resolution operato
15. int Note :: num = 5;
16. int main ()
17. {
18. // access static member function using the class name and the scope resolution
19. cout << " The value of the num is: " << Note:: func () << endl;
20. return 0;
21. }
Output
Syntax:
class_name array_name [size] ;
Example:
#include <iostream>
class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};
void main()
{
MyClass obs[4];
int i;
getch();
}
Output:
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
C++ Friend function
If a function is defined as a friend function in C++, then the protected and private data of a class can be
accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class starting
with the keyword friend.
o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot membership operator with
the member name.
o It can be declared either in the private or the public part.
Output:
Length of box: 10
1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }
Output:
10
In the above example, min() function is friendly to two classes, i.e., the min() function can access the private
members of both the classes A and B.
1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }
Output:
value of x is : 5
In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend of class A.
Class B can access the private members of class A.
o methods,
o constructors, and
o indexed properties
1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b){
6. return a + b;
7. }
8. static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
14. Cal C; // class object declaration.
15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }
Output:
30
55
1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5. int mul(int a,int b)
6. {
7. return a*b;
8. }
9. float mul(double x, int y)
10. {
11. return x*y;
12. }
13. int main()
14. {
15. int r1 = mul(6,7);
16. float r2 = mul(0.2,3);
17. std::cout << "r1 is : " <<r1<< std::endl;
18. std::cout <<"r2 is : " <<r2<< std::endl;
19. return 0;
20. }
Output:
r1 is : 42
r2 is : 0.6
When the compiler shows the ambiguity error, the compiler does not run the program.
o Type Conversion.
o Function with default arguments.
o Function with pass by reference.
o Type Conversion:
Let's see a simple example.
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(float);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(float j)
10. {
11. std::cout << "Value of j is : " <<j<< std::endl;
12. }
13. int main()
14. {
15. fun(12);
16. fun(1.2);
17. return 0;
18. }
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int,int);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(int a,int b=9)
10. {
11. std::cout << "Value of a is : " <<a<< std::endl;
12. std::cout << "Value of b is : " <<b<< std::endl;
13. }
14. int main()
15. {
16. fun(12);
17.
18. return 0;
19. }
Operator overloading is used to overload or redefines most of the operators available in C++. It is used to
perform the operation on the user-defined data type.
For example, C++ provides the ability to add the variables of the user-defined data type that is applied to
the built-in data types.
The advantage of Operators overloading is to perform different operations on the same operand.
Where the return type is the type of value returned by the function.
operator op is an operator function where op is the operator being overloaded, and the operator is the
keyword.
o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member function can be
used to overload those operators.
o When unary operators are overloaded through a member function take no explicit arguments, but,
if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit argument, and
if they are overloaded through a friend function takes two explicit arguments.
1. #include <iostream>
2. using namespace std;
3. class Test
4. {
5. private:
6. int num;
7. public:
8. Test(): num(8){}
9. void operator ++() {
10. num = num+2;
11. }
12. void Print() {
13. cout<<"The Count is: "<<num;
14. }
15. };
16. int main()
17. {
18. Test tt;
19. ++tt; // calling of a function "void operator ++()"
20. tt.Print();
21. return 0;
22. }
Output:
C - Bit Fields
Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status,
as follows −
struct {
unsigned int widthValidated;
unsigned int heightValidated;
} status;
This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1 in each of
the variables. The C programming language offers a better way to utilize the memory space in such
situations.
If you are using such variables inside a structure then you can define the width of a variable which tells the
C compiler that you are going to use only those number of bytes. For example, the above structure can be
re-written as follows −
struct {
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be used to
store the values.
If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will use 4
bytes. However as soon as you have 33 variables, it will allocate the next slot of the memory and it will
start using 8 bytes. Let us check the following example to understand the concept −
Live Demo
#include <stdio.h>
#include <string.h>
int main( ) {
printf( "Memory size occupied by status1 : %d\n", sizeof(status1));
printf( "Memory size occupied by status2 : %d\n", sizeof(status2));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by status1 : 8
Memory size occupied by status2 : 4
1
type
An integer type that determines how a bit-field's value is interpreted. The type may be int, signed int,
or unsigned int.
2
member_name
The name of the bit-field.
3
width
The number of bits in the bit-field. The width must be less than or equal to the bit width of the
specified type.
Live Demo
#include <stdio.h>
#include <string.h>
struct {
unsigned int age : 3;
} Age;
int main( ) {
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
When the above code is compiled it will compile with a warning and when executed, it produces the
following result −
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0
Constructor in C++?
A constructor is a particular member function having the same name as the class name. It calls
automatically whenever the object of the class is created.
Syntax:
The syntax of the constructor in C++ are given below.
1. class class_name
2. {
3. ……….
4. public
5. class_name ([parameter list])
6. {
7. ……………….
8. }
9. };
In the above-given syntax, class_name is the constructor's name, the public is an access specifier, and the
parameter list is optional.
Example of Constructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class hello { // The class
5. public: // Access specifier
6. hello () { // Constructor
7. cout << "Hello World! Program in C++ by using Constructor";
8. }
9. void display() {
10. cout <<"Hello World!" <<endl;
11. }
12. };
13. int main() {
14. hello myObj; /
15. return 0;
16. }
There are four types of constructors used in C++.
o Default constructor
o Dynamic constructor
o Parameterized constructor
o Copy constructor
Default Constructor: A constructor is a class which accepts no parameter and is called a default
constructor. If there is no constructor for a class, the compiler implicitly creates a default constructor.
1. class class_name {
2. private:
3. ………..
4. ………..
5. public:
6. class_name ()
7. {
8. …….
9. }
10. }
If no constructor is defined in the class, the compiler automatically creates the class's default constructor.
Example:
1. class student {
2. private:
3. ………..
4. ………..
5. public:
6. student ()
7. {
8. …….
9. }
10. }
Parameterised Constructor: A constructor is a class that can take parameters and is called a parameterized
constructor. It is used to initialize objects with a different set of values.
1. Class classname
2. {
3. …………;
4. …………;
5. Public:
6. Class name (parameter list)
7. {
8. ………….;
9. }
10. };
Copy Constructor: A particular constructor used for the creation of an existing object. The copy
constructor is used to initialize the thing from another of the same type.
Syntax:
In the above syntax, the object refers to a thing used to initialize another object.
Dynamic Constructor: This type of constructor can be used to allocate the memory while creating the
objects. The data members of an object after creation can be initialized, called dynamic initialization.
Destructor in C++?
Destructors have the same class name preceded by (~) tilde symbol. It removes and destroys the memory
of the object, which the constructor allocated during the creation of an object.
Syntax:
The syntax of destructor in C++ are given below.
1. class class_name
2. {
3. …………….;
4. …………….;
5. public:
6. xyz(); //constructor
7. ~xyz(); //destructor
8. };
The Destructor has no argument and does not return any value, so it cannot be overloaded.
Example of Destructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class Hello {
5. public:
6. //Constructor
7. Hello () {
8. cout<< "Constructor function is called" <<endl;
9. }
10. //Destructor
11. ~Hello () {
12. cout << "Destructor function is called" <<endl;
13. }
14. //Member function
15. void display() {
16. cout <<"Hello World!" <<endl;
17. }
18. };
19. int main(){
20. //Object created
21. Hello obj;
22. //Member function called
23. obj.display();
24. return 0;
25. }
Purpose of To allocate memory to the object, we used a To deallocate the memory that the constructor
use constructor in C++. allocated to an object for this purpose, we use the
concept of destructor in C++.
Arguments It may or may not contain arguments. It cannot contain the arguments.
Calling It is called automatically whenever the object of It is called automatically whenever the program
the class is created. terminates.
Return type It has return types. It doesn't have any return type.
Special While declaring constructor in the C++ While declaring a destructor in C++ programming
symbol programming language, there is no requirement of language, a particular symbol is required, i.e., tilde
the special symbol. symbol.
In numbers We can use more than one constructor in our We cannot use more than one destructor in the
program. program.
Execution They are executed in successive order. They are executed in the constructor's reverse
Order order; basically, they are the inverse of the
constructors.
Types Constructor has four types: Destructors have no classes.
o Default constructor
o Copy constructor
o Parameterized constructor
o Dynamic constructor
Declaration The following declaration is used for creating a The following declaration is used for creating a
constructor: destructor:
class class_name class class_name
{ {
………. …………….;
public …………….;
class_name ([parameter list]) public:
{ ~xyz();
………………. {
} …………
}; };