Reputation: 9512
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
Upvotes: 4
Views: 182
Reputation: 42889
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.
Upvotes: 8
Reputation: 14174
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.
Upvotes: 3