C++ Default Constructor
C++ Default Constructor
C++ Default Constructor
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data
members of new object generally. The constructor in C++ has the same name as class or structure.
o Default constructor
o Parameterized constructor
12.7K
Eve Cam: Protect Your Home AND Your PRIVACY! Best Smart Home Camera?!
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output:
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
1. class A
2. {
3. A(A &x) // copy constructor.
4. {
5. // copyconstructor.
6. }
7. }
In the above case, copy constructor can be called in the following ways:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
Output:
20
o When we initialize the object with another existing object of the same class type. For example, Student s1 = s2, where
Student is the class.
o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by value.
Shallow Copy
o The default copy constructor can only produce the shallow copy.
o A Shallow copy is defined as the process of creating the copy of an object by copying data of all the member variables as it
is.
1. #include <iostream>
2.
3. using namespace std;
4.
5. class Demo
6. {
7. int a;
8. int b;
9. int *p;
10. public:
11. Demo()
12. {
13. p=new int;
14. }
15. void setdata(int x,int y,int z)
16. {
17. a=x;
18. b=y;
19. *p=z;
20. }
21. void showdata()
22. {
23. std::cout << "value of a is : " <<a<< std::endl;
24. std::cout << "value of b is : " <<b<< std::endl;
25. std::cout << "value of *p is : " <<*p<< std::endl;
26. }
27. };
28. int main()
29. {
30. Demo d1;
31. d1.setdata(4,5,7);
32. Demo d2 = d1;
33. d2.showdata();
34. return 0;
35. }
Output:
value of a is : 4
value of b is : 5
value of *p is : 7
In the above case, a programmer has not defined any constructor, therefore, the statement Demo d2 = d1; calls the default
constructor defined by the compiler. The default constructor creates the exact copy or shallow copy of the existing object. Thus, the
pointer p of both the objects point to the same memory location. Therefore, when the memory of a field is freed, the memory of
another field is also automatically freed as both the fields point to the same memory location. This problem is solved by the user-
defined constructor that creates the Deep copy.
Deep copy
Deep copy dynamically allocates the memory for the copy and then copies the actual value, both the source and copy have distinct
memory locations. In this way, both the source and copy are distinct and will not share the same memory location. Deep copy
requires us to write the user-defined constructor.
1. #include <iostream>
2. using namespace std;
3. class Demo
4. {
5. public:
6. int a;
7. int b;
8. int *p;
9.
10. Demo()
11. {
12. p=new int;
13. }
14. Demo(Demo &d)
15. {
16. a = d.a;
17. b = d.b;
18. p = new int;
19. *p = *(d.p);
20. }
21. void setdata(int x,int y,int z)
22. {
23. a=x;
24. b=y;
25. *p=z;
26. }
27. void showdata()
28. {
29. std::cout << "value of a is : " <<a<< std::endl;
30. std::cout << "value of b is : " <<b<< std::endl;
31. std::cout << "value of *p is : " <<*p<< std::endl;
32. }
33. };
34. int main()
35. {
36. Demo d1;
37. d1.setdata(4,5,7);
38. Demo d2 = d1;
39. d2.showdata();
40. return 0;
41. }
Output:
value of a is : 4
value of b is : 5
value of *p is : 7
In the above case, a programmer has defined its own constructor, therefore the statement Demo d2 = d1; calls the copy
constructor defined by the user. It creates the exact copy of the value types data and the object pointed by the pointer p. Deep
copy does not create the copy of a reference type variable.
It initializes the new object with the existing object. It assigns the value of one object to another
object.
Both the existing object and new object shares the different Both the existing object and new object shares
memory locations. the same memory location.
If a programmer does not define the copy constructor, the compiler If we do not overload the "=" operator, the
will automatically generate the implicit default copy constructor. bitwise copy will occur.
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like
constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
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. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }
Output:
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. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }
Output:
C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static
members. In C++, static can be field, method, constructor, class, properties, operator and event.
Advantage of C++ static keyword
Memory efficient: Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it
belongs to the type, so it will not get memory each time when instance is created.
It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee
etc.
Play Videox
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. static float rateOfInterest;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. }
13. void display()
14. {
15. cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
16. }
17. };
18. float Account::rateOfInterest=6.5;
19. int main(void) {
20. Account a1 =Account(201, "Sanjay"); //creating an object of Employee
21. Account a2=Account(202, "Nakul"); //creating an object of Employee
22. a1.display();
23. a2.display();
24. return 0;
25. }
Output:
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name;
7. static int count;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. count++;
13. }
14. void display()
15. {
16. cout<<accno<<" "<<name<<endl;
17. }
18. };
19. int Account::count=0;
20. int main(void) {
21. Account a1 =Account(201, "Sanjay"); //creating an object of Account
22. Account a2=Account(202, "Nakul");
23. Account a3=Account(203, "Ranjana");
24. a1.display();
25. a2.display();
26. a3.display();
27. cout<<"Total Objects are: "<<Account::count;
28. return 0;
29. }
Output:
201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3
C++ Structs
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects
such as Rectangle, color, Point, etc.
Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after
creation of struct.
C++ Structure is a collection of different data types. It is similar to the class that holds different types of data.
1. struct structure_name
2. {
3. // member declarations.
4. }
In the above declaration, a structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside
the curly braces, we can declare the member variables of different types. Consider the following situation:
Play Videox
1. struct Student
2. {
3. char name[20];
4. int id;
5. int age;
6. }
In the above case, Student is a structure contains three variables name, id, and age. When the structure is declared, no memory is
allocated. When the variable of a structure is created, then the memory is allocated. Let's understand this scenario.
Student s;
Here, s is a structure variable of type Student. When the structure variable is created, the memory will be allocated. Student
structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will
be 2*4 = 8. The total memory occupied by the s variable is 9 byte.
For example:
1. s.id = 4;
In the above statement, we are accessing the id field of the structure Student by using the dot(.) operator and assigns the value 4
to the id field.
Output:
1. #include <iostream>
2. using namespace std;
3. struct Rectangle {
4. int width, height;
5. Rectangle(int w, int h)
6. {
7. width = w;
8. height = h;
9. }
10. void areaOfRectangle() {
11. cout<<"Area of Rectangle is: "<<(width*height); }
12. };
13. int main(void) {
14. struct Rectangle rec=Rectangle(4,6);
15. rec.areaOfRectangle();
16. return 0;
17. }
Output:
Structure Class
If access specifier is not declared explicitly, then by default If access specifier is not declared explicitly, then by
access specifier will be public. default access specifier will be private.
The instance of the structure is known as "Structure The instance of the class is known as "Object of the
variable". class".
C++ Enumeration
Enum in C++ is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions
(NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly.
C++ Enums can be thought of as classes that have fixed set of constants.
1. #include <iostream>
2. using namespace std;
3. enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
4. int main()
5. {
6. week day;
7. day = Friday;
8. cout << "Day: " << day+1<<endl;
9. return 0;
10. }
Output:
Day: 5
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.
In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the
program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator.
Play Videox
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.
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }
Output:
Length of box: 10
Let's see a simple example when the function is friendly to two classes.
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.
C++ Friend class
A friend class can access both private and protected members of the class in which it has been declared as friend.
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.
Play Videox
Let's try to understand the concept of call by value in C++ language by the example given below:
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Output:
Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, value
changed inside the function, is reflected inside as well as outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.
Let's try to understand the concept of call by reference in C++ language by the example given below:
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
1 A copy of value is passed to the function An address of value is passed to the function
2 Changes made inside the function is not reflected on Changes made inside the function is reflected
other functions outside the function also
3 Actual and formal arguments will be created in Actual and formal arguments will be created in same
different memory location memory location