Copy constructor in C++
A copy constructor is a method of a class which initializes an object using another object of the same class. A copy constructor can be called in various scenarios. For example:
- In the case where an object of a class is returned by value.
- In the case of an object of a class being passed, by value, to a function as an argument.
A copy constructor can also be defined by a user; in this case, the default copy constructor is not called.
Note: A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references to a file (for example).
Syntax
A copy constructor has the following function declaration:
Note: The object to a copy constructor is always passed by reference.
If the object is passed by value, then its copy constructor will be invoked and it would be stuck in an infinite recursion.
Code
The following snippet illustrates an example of a copy constructor defined in the class Coordinate.
#include<iostream>using namespace std;class Coordinate{private:int x_cor, y_cor;public:// default constructorCoordinate(int x, int y){x_cor = x;y_cor = y;}// Copy constructorCoordinate(const Coordinate &cor){// Note how you can access the private attributes of// the object class in the copy constructor,x_cor = cor.x_cor;y_cor = cor.y_cor;}int get_x_cor(){return x_cor;}int get_y_cor(){return y_cor;}};int main(){// default constructor called hereCoordinate cor1(2, 4);// Copy constructor is called hereCoordinate cor2 = cor1;// Another copy constructor is called hereCoordinate cor3(cor1);// Showing resultscout << "cor1 = (" << cor1.get_x_cor() << "," << cor1.get_y_cor() << ")" << endl;cout << "cor2 = (" << cor2.get_x_cor() << "," << cor2.get_y_cor() << ")" << endl;cout << "cor3 = (" << cor3.get_x_cor() << "," << cor3.get_y_cor() << ")" << endl;return 0;}
Explanation
Let’s take a closer look at the code:
-
Line 4, we define a class named
Coordinate. -
Line 7, we define
x_corandy_corasprivatein classCoordinate. -
Line 12-16, we define the default constructor of class
Coordinate. -
Line 19-25, we define the copy constructor and assigned values of
corobjects to private members ofCoordinateclass (x_corandy_cor.) -
Line 27-29 and 32-34, we defined getter of
x_corandy_correspectively. -
Line 40, we created object
cor1with parameters (2,4). -
Line 43, we created another object
cor2and copied values ofcor1tocor2by using copy constructor. -
Line 45, we created object
cor3and copied values ofcor1using another method of copy constructor. -
Line 48-50, we print values of
cor1,cor2andcor3respectively.
Free Resources