C++ Program using copy constructor


In this program, You will learn how to implement copy constructor in C++.


1. Test( ) { },

2. Test(obj) { },

3. Test t3 = t2


Example: How to implement copy constructor in C++

Run it Now
#include<iostream>
using namespace std;

class Test {
   int x, y;
public:

   Test(int a, int b) {
       x = a;
       y = b;
   }

   Test(Test &obj) {
       x = obj.x;
       y = obj.y;
   }

   void display() {
     cout << "The value of x is :" << x;
     cout << "\nThe value of y is :" << y << endl;
   }
};

int main() {

   int a, b;

   Test t1(10, 20);
   Test t2(t1);
   Test t3 = t2;

   t1.display();
   t2.display();
   t3.display();

   return 0;
}

Output:

The value of x is :10
The value of y is :20
The value of x is :10
The value of y is :20
The value of x is :10
The value of y is :20