Example For Copy Constructor In C++

A copy constructor is similar to a constructor except that it take a reference to its class type. A Copy constructor is used to copy an object into another object of its type. Like a constructor, a copy constructor to has no return type.

Although Copy constructor can be overloaded we usually don't do so. The Compiler calls copy constructor implicitly as soon as an object is initialized to another object of its type.

A copy constructor is called when:

  • Initializing an object to another object.
  • Passing an object to a function.
  • Returning an object from a function

Simple Example Program For Copy Constructor In C++

#include<iostream> using namespace std; class Copy_Constructor{ int a; public: Copy_Constructor(int x){ cout<<"Constructor called "<<endl; a = x; } Copy_Constructor(Copy_Constructor &s){ cout<<"Copy Constructor called"<<endl; a=s.a; } void print(){ cout<<"The value of a is :"<<a<<endl; } }; int main(){ Copy_Constructor s1(8); //Constructor Copy_Constructor s2(s1); //Copy Constructor Copy_Constructor s3 = s1; // Copy Constructor (another way) s1.print(); s2.print(); s3.print(); return 0; }


Constructor called
Copy Constructor called
Copy Constructor called
The value of a is :8
The value of a is :8
The value of a is :8

Explanation of the program

In this program, object s2 passes the object s1 as the argument. Hence the compiler automatically invokes the copy constructor. Also, when a new object s3 is created, the object s1 is copied into it which again mean that the argument passed will be an object. Hence one again the copy constructor is invoked.