Programming‎ > ‎C++‎ > ‎Programming Tips‎ > ‎Misc‎ > ‎

Copy Constructor

The copy constructor is used to initialize an object with a different object of the same type, and the copy assignment operator is used to copy the value from one object to another of the same type.
class MyClass
      MyClass();                                            // default constructor
      MyClass(const MyClass& rhs);                  // copy constructor
      MyClass& operator=(const MyClass& rhs)    // copy assignment operator
MyClass m1;                                                 // invoke default constructor
MyClass m2(m1);                                           // invoke copy constructor
m1 = m2;                                                     // invoke copy assignement operator
Read carefully wen you see what appears to be an assignment, because the "=" syntax can also be used to call the copy constructor.
MyClass m3 = m2;                                          // invoke copy constructor!
If a new object is being defined (such as m3 in the statement above), a constructor has to be called; it can't be an assignment. If no new object is being defined (such as "m1 = m2" statement above), no constructor can be involved, so it's an assignment.
The copy constructor is a particularly important function, because it defines how an object is passed by value.
bool doSomeThing(MyClass m);
MyClass aMyClass;
if(true == doSomeThing(aMyClass)) ...
The copying of aMyClass to m is done by MyClass's copy constructor. Pass-by-value means "call the copy constructor". Pass-by-reference-to-const is typically a better choice.