-1

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 Answers2

2

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
1

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.

David G
  • 94,763
  • 41
  • 167
  • 253
  • It seems like you're right, unless I explicitly overload B& B::operator=(B const& b) my self, It does what you say it does. – Michael Papkov Jun 24 '15 at 20:21