Copy Constructor

What is a copy constructor? 

The copy constructor in C++ is used to copy data of one object to another.
A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype: 

    ClassName (const ClassName &old_obj); 
 Example
#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:

// initialize variables with parameterized constructor
Wall(double len, double hgt) {
length = len;
height = hgt;
}

// copy constructor with a Wall object as parameter
// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}

double calculateArea() {
return length * height;
}
};

int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2
Wall wall2 = wall1;

// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}
 
Output
 
 
In this program, we have used a copy constructor to copy the contents of one object 
of the Wall class to another. 
The code of the copy constructor is: 
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
 
Notice that the parameter of this constructor has the address of an object of the Wall class.

We then assign the values of the variables of the obj object to the corresponding 
variables of the object calling the copy constructor. This is how the contents of the object
 are copied.

In main(), we then create two objects wall1 and wall2 and then copy the contents of wall1 to
 wall2: 
 
// copy contents of wall1 to wall2
Wall wall2 = wall1;
Here, the wall2 object calls its copy constructor by passing the address of the wall1 object as
 its argument i.e. &obj = &wall1. 
When is  copy constructor called? 

In C++, a Copy Constructor may be called in the following cases: 
1. When an object of the class is returned by value. 
2. When an object of the class is passed (to a function) by value as an argument. 
3. When an object is constructed based on another object of the same class. 
4. When the compiler generates a temporary object.
 
 
 

No comments:

Post a Comment