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

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.