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:
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).
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.
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;}
Let’s take a closer look at the code:
Line 4, we define a class named Coordinate
.
Line 7, we define x_cor
and y_cor
as private
in class Coordinate
.
Line 12-16, we define the default constructor of class Coordinate
.
Line 19-25, we define the copy constructor and assigned values of cor
objects to private members of Coordinate
class (x_cor
and y_cor
.)
Line 27-29 and 32-34, we defined getter of x_cor
and y_cor
respectively.
Line 40, we created object cor1
with parameters (2,4).
Line 43, we created another object cor2
and copied values of cor1
to cor2
by using copy constructor.
Line 45, we created object cor3
and copied values of cor1
using another method of copy constructor.
Line 48-50, we print values of cor1
, cor2
and cor3
respectively.