What is a Copy Constructor in C++ ? Give an example
![]() Don't want to miss a single bit? Subscribe By Email for Daily Jobs |
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
- What are Constructors and Destructors in C++ ?
- What are Friend Functions and Friend Classes in C++ ?
- What is Operator Overloading in C++ ?
- What is Multiple Inheritance in C++ ? Explain with an example
- What are static Data and Static Member Functions in C++ ?


