简体   繁体   中英

c++ operator= weird behviour

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM