What is a Copy Constructor in C++ ? Give an example

October 28, 2007 · Filed Under C++ Questions, Placement Questions 



Don't want to miss a single bit? Subscribe By Email for Daily Jobs

Enter your email address :

All the latest from JobsAdda on Jobsadda.com delivered to your mailbox everyday.

Copy constructor is a type of constructor which constructs an object by copying the state from another object of the same class. Whenever an object is copied, another object is created and in this process the copy constructor gets called. If the class of the object being copied is x, the copy constructor’s signature is usually x::x (const x&).

Let’s take an example to illustrate this:

class Complex

{

int real, img;

public:

Complex (int, int);

Complex (const Complex& source); //copy constructor

};

Complex:: Complex (const Complex& source)

{

this.real = source.real;

this.img = source.img;

}

main ()

{

Complex a (2, 3);

Complex b = a; // this invokes the copy constructor

}

A copy constructor is called whenever an object is passed by value, returned by value or explicitly copied.

Related Articles


Get Latest JobsAdda.com Jobs, news & updates  via Email