4

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 
3
  • 6
    Because the language specifies that Type var = value invokes Type's copy constructor and not its assignment operator. Commented Apr 14, 2014 at 15:09
  • 2
    Including the output of your program would be good. Commented Apr 14, 2014 at 15:10
  • 1
    Note that copy constructor need not be called at all. The compiler is allowed to optimize it away (see Copy elision). This is an exception to the rule that compiler optimizations do not change the observable behaviour of the program (cout statements in your case). Commented Apr 14, 2014 at 15:20

2 Answers 2

8

Because is not an actual assignment since you declare u at the same time. Thus, the constructor is called instead of the assignment operator. And this is more efficient because if it wasn't for this feature there would have been the redundancy of calling first a default constructor and then the assignment operator. This would have evoked the creation of unwanted copies and thus would had deteriorate the performance of the C++ model significantly.

Sign up to request clarification or add additional context in comments.

Comments

3

Because that's the declaration and initialization of a variable, not the assigment of a value to an existing variable. In the context of a variable declaration, = is just syntactic sugar for passing a parameter to the ctor.

2 Comments

so the use of the assignment operator is always linked to the existence of a previously declared object?
@dabadaba yes. Assigment means giving a new value to an existing variable. Giving a value to a new variable is initialization, which is the work of ctors.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.