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

前端 未结 6 1425
旧巷少年郎
旧巷少年郎 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:07

    I've changed the names of your structs to make the reason obvious:

    struct Animal {}; 
    struct Bear : Animal {}; 
    Animal a; 
    Bear b; 
    a = b; // line 1 
    b = a; // line 2 
    

    Clearly, any Bear is also an Animal, but not every Animal can be considered a Bear.

    Because every B "isa" A, any instance of B must also be an instance of A: by definition it has the same members in the same order as any other instance of A. Copying b into a loses the B-specific members, but completely fills the members of a resulting in a struct that satisfies the requirements of A. Copying a to b, on the other hand, may leave b incomplete because B could have more members than A. That's hard to see here because neither A nor B has any members at all, but this is why the compiler allows one assignment and not the other.

提交回复
热议问题