The constructor can accept arguments of any data type including user-defined data types, exclusive of the class to which it belongs. Consider the following examples shown in Table.
Table: Copy Constructors
In the example (a), an argument of the constructor is same as that of its class. Hence, this declaration is wrong. It is possible to pass reference of object to the constructor. Such declaration is known as copy constructor. The example (b) is valid and can be used to copy constructor.
When we pass an object by value into a function, a temporary copy of that object is created. All copy constructors require one argument, with reference to an object of that class. Using copy constructors, it is possible for the programmers to declare and initialize one object using reference of another object. Thus, whenever a constructor is called, a copy of an object is created.
9.11 Write a program to pass an object with reference to constructor. Declare and initialize other objects.
Explanation: In the above program, class num is declared with one integer member variable n and three constructors. In function main(), the object J is created and 50 is passed to constructor. It is passed by value; hence, constructor with one argument is invoked. When object K is created with one object, the copy constructor is invoked, object is passed, and data member is initialized. The object L is created with assignment with object J; this time also copy constructor is invoked. The compiler copies all the members of object J to destination object L in the assignment statement num L = J. When object is created without any value, such as M, default constructor is invoked. The copy constructor is not invoked even if object J is assigned to object M.
The data member variables that are dynamically allocated should be copied to the target object explicitly by using assignment statement or by copy constructor as per the following statement:
num L = J; // copy constructor is executed
Consider the statement
M = J;
Here, M and J are predefined objects. In this statement, copy constructor is not executed. The member variables of object J are copied to object M member by member. An assignment statement assigns value of one entity to another.
The statement num L = J; initializes object L with J during definition. The member variables of J are copied member by member into object L. This statement invokes constructor. This statement can be written as num L (J), which we frequently use to pass values to the constructor.