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:
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.
{
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.
No comments:
Post a Comment