Why is an assignment to a base class valid, but an assignment to a derived class a compilation error?

前端 未结 6 1407
旧巷少年郎
旧巷少年郎 2021-01-31 08:27

This was an interview question. Consider the following:

struct A {}; 
struct B : A {}; 
A a; 
B b; 
a = b;
b = a; 

Why does b = a;

6条回答
  •  清歌不尽
    2021-01-31 09:03

    Because the implicitly declared copy assignment operator of B hides the implicitly declared copy assignment operator of A.

    So for the line b = a, only the the operator= of B is a candidate. But its parameter has type B const&, which cannot be initialized by an A argument (you would need a downcast). So you get an error.

提交回复
热议问题