In this C++ tutorial, you will learn about Copy Constructor, and how to use this technique to take an object of the same class type as parameter in the constructor, and create a new object with the attribute values of the argument object.

C++ Copy Constructor

A Copy Constructor is a constructor which takes an object of same class type as parameter and uses this object to initialise a new object.

There are two types of constructors based on whether this constructor is explicitly defined in the class or not.

  • Default Copy Constructor
  • User Defined Copy Constructor

Default Copy Constructor

By default, if no copy constructor is explicitly defined for a class in the class definition, compiler itself defines a default Copy Constructor.

This default Copy Constructor takes an object of the same class type and creates a new object with the properties set with values from the object received as parameter.

Example

In the following program, we create an object a1 of type A, and then use default Copy Constructor to create a new object a2 from a1.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

class A {
public:
    int x;
    int y;
    
    A(int _x, int _y) {
        x = _x;
        y = _y;
    }
};

int main() {
    A a1(3, 4);
    A a2(a1);
    cout << "(x, y) : "<< a2.x << ", " << a2.y << endl;
}

Output

(x, y) : 3, 4
Program ended with exit code: 0

User-defined Copy Constructor

As the name suggests, we may override the default behaviour by defining a Copy Constructor in the class definition.

By using this type of Copy Constructor we can control the initialisation of new object from the given object.

Example

In the following program, we define a class A with copy constructor. We shall create an object a1 of type A, and then use the Copy Constructor to create a new object a2 from a1.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

class A {
public:
    int x;
    int y;
    
    A(int _x, int _y) {
        x = _x;
        y = _y;
    }
    
    A(A &a) {
        x = a.x;
        y = 0;
    }
};

int main() {
    A a1(3, 4);
    A a2(a1);
    cout << "(x, y) : "<< a2.x << ", " << a2.y << endl;
}

Output

(x, y) : 3, 0
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned what a Copy Constructor is, what are default and user-defined Copy Constructors, and their usage, with the help of examples.