C++
Important Links
What is 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.
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors iitialize values to object members after storage is allocated to the object.
class A
{
int x;
public:
A(); //Constructor
};
While defining a contructor you must remeber that the name of constructor will be same as the name of the class, and contructors never have return type.
Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.
Example :-
class A
{
int i;
public:
A(); //Constructor declared
};
A::A() // Constructor definition
{
i=1;
}
Types of constructor :-
There are three types of constructors in C++.
C++ Default Constructor :-
Default constructor is the constructor which doesn't take any argument. It has no parameter.
It is invoked at the time of creating object.
Example :-
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output :-
Default Constructor Invoked
Example :-
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}
In this case, as soon as the object is created the constructor is called which initializes its data members.
A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly.
Example :-
class Cube
{
public:
int side;
};
int main()
{
Cube c;
cout << c.side;
}
Output :-
In this case, default constructor provided by the compiler will be called which will initialize the object data members to default value, that will be 0 in this case.
Parameterized Constructor :-
A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.
Example :-
#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<
}
};
int main(void) {
Employee e1 =Employee(101, "itechxpert", 890000); //creating an object of Employee
Employee e2=Employee(102, "itechtuto", 59000);
e1.display();
e2.display();
return 0;
}
Output :-
102 itechtuto 59000
Example :-
class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized construcor in above case, we have initialized 3 objects with user defined values. We can have any number of parameters in a constructor.
Copy Constructor :-
A copy constructor is a member function which initializes an object using another object of the same class.
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to −
Syntax :-
A copy constructor is a like a normal parameterized Constructor, but which parameter is the same class object. Copy constructor uses to initialize an object using another object of the same class.
Syntax of Copy Constructor :-
class class_name {
public:
class_name(class_name & obj) {
// obj is same class another object
// Copy Constructor code
}
//... other Variables & Functions
}
Example :-
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
Output :-
p2.x = 10, p2.y = 15
Example :-
#include<iostream>
using namespace std;
class Samplecopyconstructor
{
private:
int x, y; // data
public:
Samplecopyconstructor(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Samplecopyconstructor (const Samplecopyconstructor &sam)
{
x = sam.x;
y = sam.y;
}
void display()
{
cout<
}
};
int main()
{
Samplecopyconstructor obj1(10, 15); // Normal constructor
Samplecopyconstructor obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
Output :-
Copy constructor : 10 15
When is copy constructor called? :-
In C++, a Copy Constructor may be called in following cases:
Example :-
#include<iostream>
#include<conio.h>
using namespace std;
class Example {
// Member Variable Declaration
int a, b;
public:
//Normal Constructor with Argument
Example(int x, int y) {
// Assign Values In Constructor
a = x;
b = y;
cout << "\nIm Constructor";
}
//Copy Constructor with Obj Argument
Example(const Example& obj) {
// Assign Values In Constructor
a = obj.a;
b = obj.b;
cout << "\nIm Copy Constructor";
}
void Display() {
cout << "\nValues :" << a << "\t" << b;
}
};
int main() {
//Normal Constructor Invoked
Example Object(10, 20);
//Copy Constructor Invoked - Method 1
Example Object2(Object);
//Copy Constructor Invoked - Method 2
Example Object3 = Object;
Object.Display();
Object2.Display();
Object3.Display();
// Wait For Output Screen
getch();
return 0;
}
Output :-
Im Copy Constructor
Im Copy Constructor
Values :10 20
Values :10 20
Values :10 20
Shallow Copy Constructor :-
The concept of shallow copy constructor is explained through an example. Two students are entering their details in excel sheet simultaneously from two different machines shared over a network. Changes made by both of them will be reflected in the excel sheet. Because same excel sheet is opened in both locations. This is what happens in shallow copy constructor. Both objects will point to same memory location.
Shallow copy copies references to original objects. The compiler provides a default copy constructor. Default copy constructor provides a shallow copy as shown in below example. It is a bit-wise copy of an object.
Shallow copy constructor is used when class is not dealing with any dynamically allocated memory.
In the below example you can see both objects, c1 and c2, points to same memory location. When c1.concatenate() function is called, it affects c2 also. So both c1.display() and c2.display() will give same output.
Example :-
#include<iostream>
#include<cstring>
using namespace std;
class CopyConstructor
{
char *s_copy;
public:
CopyConstructor(const char *str)
{
s_copy = new char[16]; //Dynamic memory allocation
strcpy(s_copy, str);
}
void concatenate(const char *str)
{
strcat(s_copy, str); //Concatenating two strings
}
~ CopyConstructor (){ delete [] s_copy;}
void display()
{
cout<
}
};
int main()
{
CopyConstructor c1("Copy");
CopyConstructor c2=c1; //Copy constructor
c1.display();
c2.display();
c1.concatenate("Constructor"); //c1 is invoking concatenate()
c1.display();
c2.display();
return 0;
}
Output :-
Copy
CopyConstructor
CopyConstructor
Deep Copy Constructor :-
You are supposed to submit an assignment tomorrow and you are running short of time, so you copied it from your friend. Now you and your friend have same assignment content, but separate copies. Therefore any modifications made in your copy of assignment will not be reflected in your friend's copy. This is what happens in deep copy constructor.
Deep copy allocates separate memory for copied information. So the source and copy are different. Any changes made in one memory location will not affect copy in the other location. When we allocate dynamic memory using pointers we need user defined copy constructor. Both objects will point to different memory locations.
Example :-
In the previous example you can see when c1 called concatenate(), changes happens in both c1 and c2, because both are pointing to same memory location.
In the below example you can see user defined copy constructor i.e deep copy constructor. Here both c1 and c2 points to different memory location. So changes made in one location will not affect the other.
Example :-
#include<iostream>
#include<cstring>
using namespace std;
class CopyConstructor
{
char *s_copy;
public:
CopyConstructor (const char *str)
{
s_copy = new char[16]; //Dynamic memory alocation
strcpy(s_copy, str);
}
CopyConstructor (const CopyConstructor &str)
{
s_copy = new char[16]; //Dynamic memory alocation
strcpy(s_copy, str.s_copy);
}
void concatenate(const char *str)
{
strcat(s_copy, str); //Concatenating two strings
}
~ CopyConstructor(){ delete [] s_copy;}
void display()
{
cout<<s_copy<<endl;
}
};
int main()
{
CopyConstructor c1("Copy");
CopyConstructor c2=c1;//copy constructor
c1.display();
c2.display();
c1.concatenate("Constructor"); //c1 is invoking concatenate()
c1.display();
c2.display();
return 0;
}
Output :-
Copy
CopyConstructor
Copy