Advertisement

C++ Program using the copy constructor


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


1. Test( ) { },

2. Test(obj) { },

3. Test t3 = t2

Example: How to implement a copy constructor in C++

#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 << "value of x is:" << x;
     cout << "\nvalue 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:

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