What is a copy constructor? Explain its usage and syntax and also explain how it is different from a regular constructor?
A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype:Â
ClassName (const ClassName &old_obj);
MyClass t1, t2;
MyClass t3 = t1;Â // ----> (1)
t2 = t1;Â Â Â Â Â Â Â Â Â // -----> (2)
Copy constructor is called when a new object is created from an existing object, as a copy of the existing object. Assignment operator is called when an already initialized object is assigned a new value from another existing object. In the above example (1) calls copy constructor and (2) calls assignment operator.
Comments
Leave a comment