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:

svg viewer

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 constructor
Coordinate(int x, int y)
{
x_cor = x;
y_cor = y;
}
// Copy constructor
Coordinate(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 here
Coordinate cor1(2, 4);
// Copy constructor is called here
Coordinate cor2 = cor1;
// Another copy constructor is called here
Coordinate cor3(cor1);
// Showing results
cout << "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_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.

Copyright ©2024 Educative, Inc. All rights reserved