Copy constructors
Copy Constructor is a special function which if present automatically gets executed whenever an object of a class is declared with another object as an argument.
Examples:
Student s;//default cons
Student s1(101,”abc”,15);//para cons
Student s2(s1);//copy cons
Properties
• Name of the copy constructor function is exactly same as that of the class.
• It has no return type not even void
• If present it automatically gets executed whenever an object of a class is declared with another object as an argument/parameter.
• It cannot be invoked using an object of the class.
• It is generally used to initialize an object by another object i.e. data elements of an object by data elements of another object passed as argument.
Note:
Why the argument to a copy constructor is passed by reference?
If we try to pass the arguments by value to a copy constructor( that is , if we use an employee(employee e) [student (student s) ] constructor in place of employee(employee &e))[ student (student &s), the compiler complains out of memory.
The reason being that when an argument is passed by value, a copy of it is constructed. To create a copy of the object, who works? Copy constructor. But the copy constructor is being creating a copy of the object for itself, thus it calls itself. Again the called copy constructor requires another copy so again it is called. In fact it calls itself again and again until the compiler runs out of memory. So in a copy constructor the arguments must be passed by reference, so that to make a copy of the passed object, original object is directly available.