What Is a Copy Constructor?

Copy constructor, also known as copy constructor, is a special constructor that is called by the compiler to complete the construction and initialization of some other objects based on the same class. Its formal parameter must be a reference, but it is not limited to const. Generally, a const restriction is added. This function is often used to pass and return values of user-defined types during function calls. The copy constructor calls the copy constructor and member functions of the base class. If it can, it will be called in constant mode, or in non-constant mode.

If a copy constructor is not explicitly declared in the class, then,

Copy constructor format

Declaration of copy constructor:
class class name
{
public:
Class name (formal parameter) // constructor declaration / prototype
Class name (class name & object name) // copy constructor declaration / prototype
...
};
Implementation of the copy constructor:
Class name :: class name (class name & object name) // implementation / definition of copy constructor
{Function body} [1]

Copy constructor example

  class Point
 {


 public:


 Point (int xx, int yy) {X = xx; Y = yy;}


 Point (const Point & p);


 int getX () {returnX;}


 int getY () {returnY;}


 private:


 intX, Y;
 };


 Point :: Point (const Point & p)
 {
 X = pX;
 Y = pY;
 std :: cout << "Copy constructor call" << std :: endl;
 }

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?