This is how MyClass is defined:
class MyClass { double x, y; public: MyClass (double a = 0., double b = 0.) { x = a; y = b; cout << "Using the default constructor" << endl; } MyClass (const MyClass& p) { x = p.x; y = p.y; cout << "Using the copy constructor" << endl; } MyClass operator =(const MyClass& p) { x = p.x; y = p.y; cout << "Using the assignment operator" << endl; return *this; } }; And I tested when each constructor or method is called in my main program:
int main() { cout << "MyClass p" << endl; MyClass p; cout << endl; cout << "MyClass r(3.4)" << endl; MyClass r(3.4); cout << endl; cout << "MyClass s(r)" << endl; MyClass s(r); cout << endl; cout << "MyClass u = s" << endl; MyClass u = s; cout << endl; cout << "s = p" << endl; s = p; cout << endl; } Why is the copy constructor being used in the fourth example, MyClass u = s, instead of the assignment operator?
EDIT
Including the output, as asked:
MyClass p Using the default constructor MyClass r(3.4) Using the default constructor MyClass s(r) Using the copy constructor MyClass u = s Using the copy constructor s = p Using the assignment operator Using the copy constructor
Type var = valueinvokesType's copy constructor and not its assignment operator.coutstatements in your case).