Here's how it is defined MyClass:
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 every 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 used in the fourth example MyClass u = sinstead of the assignment operator?
EDIT
Including output as given:
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
source
share