Copy Constructor in C++

Copy Constructor in C++

Copy constructor is a special type of constructor used to create the copy of an object of the class. This constructor accepts an object of the same class as arguments and copies it to another object of the class being created.

Synatx

class ClassName

{

Access_specifier:

      …

      …

      ClassName(ClassName &object)

      {

            dataMember1=object.dataMember1;

            dataMember2=object.dataMember2;

            …

            …

      }

      …

      …

};

Example

Example

In above example, Person class is defined having a copy constructor defined at line 19. It accepts object of the same class as an argument and copy the values of its data members to the newly created object (lines 21 and 22). Copy constructor is called as explained in the following example.

lines 21 and 22

In above code, an object of class Person is created at line 32 at its copy is created at line 34 by calling the copy constructor of the class Person. The output of the above code is as below showing that both the objects (p1 and p2) have the same values.

output

More Related Articles For You

    C++ Tutorial

    C++ Quizzes