Copy Constructor Program in C++

This C++ program illustrates copy-constructor in a class. A copy constructor is a special constructor for a class that is used to make a copy of an existing instance of the class. A copy-constructor looks like a constructor with an object of same class as an argument.

Here is the source code of the C++ program which illustrates copy-constructor in a class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate copy-constructor in a class
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. class Base {
  8.     int i;
  9.     public:
  10.         Base(int ii = 0): i(ii) { }
  11.         Base(const Base& b)
  12.         {
  13.             this->i = b.i;
  14.         }
  15.         void setData(int ii) { i = ii; }
  16.         int getData() { return i; }
  17. };
  18.  
  19. int main()
  20. {
  21.     Base b;
  22.  
  23.     cout << "b::getData = " << b.getData() << endl;
  24.     cout << "b::setData = 10" << endl;
  25.     b.setData(10);
  26.     cout << "b::getData = " << b.getData() << endl;
  27.     cout << "Calling copy-constructor on c" << endl;
  28.     Base c(b);
  29.     cout << "c::getData = " << c.getData() << endl;
  30. }

$ a.out
b::getData = 0
b::setData = 10
b::getData = 10
Calling copy-constructor on c
c::getData = 10

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.