Help? I really have no idea what's happening here? Why in line 3 of assignments it calls operator= of A, when its an assignment of B to B?
class A{
public:
A& operator=(const A&){cout << "A assignment" << endl;return *this;}
};
class B:public A{
public:
A& operator=(const A&){cout << "B assignment" << endl;return *this;}
};
int main() {
A a;
B b;
B b2;
a=b; // output: A assignment
b=a; // output: B assignment
b=b2; // output: A assignment WHY??
return 0;
}
You've defined an assignment operator in
B
, but there's also another implicit copy-assignment operator generated by the compiler:This is a better match than the one that takes
A const&
so it is chosen in the assignmentb = b2
(sinceb2
is aB
it doesn't require a derived-to-base conversion for the one that takes anA
). The implicit copy-assignment operator calls the copy-assignment operator of the base class which you wrote:This is why it looks like
A::operator=(A const&)
is being chosen by the assignment.