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

前端 未结 6 1585
旧巷少年郎
旧巷少年郎 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 08:57

    If I am getting interviewed then, I will explain in little philosophical way.

    a = b;
    

    is valid, because every B contains A as its part. So a can extract A from within B. However, A doesn't contain B. thus b cannot find B from within A; that's why,

    b = a;
    

    is invalid.

    [Analogically, a void* can be found in any Type*, but Type* cannot be found in void* (thus we need a cast).]

提交回复
热议问题