c++ operator= weird behviour

91 views Asked by At

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;
}
2

There are 2 answers

1
David G On BEST ANSWER

You've defined an assignment operator in B, but there's also another implicit copy-assignment operator generated by the compiler:

B& B::operator=(B const&);

This is a better match than the one that takes A const& so it is chosen in the assignment b = b2 (since b2 is a B it doesn't require a derived-to-base conversion for the one that takes an A). The implicit copy-assignment operator calls the copy-assignment operator of the base class which you wrote:

B& B::operator=(B const& b) {
    A::operator=(b);
    return *this;
}

This is why it looks like A::operator=(A const&) is being chosen by the assignment.

2
Cheers and hth. - Alf On

There's still a compiler-generated assignment operator in class B (it's overloaded); unlike how this works with constructors, defining one or more assignment operator overloads does not prevent the compiler from generating a copy assignment operator when one is lacking. The compiler generated one calls A::operator=. And it's the better match for an argument of type B.