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

前端 未结 6 1404
旧巷少年郎
旧巷少年郎 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 every B is an A, but not every A is a B.

    Edited following comments to make things a bit clearer (I modified your example):

    struct A {int someInt;}; 
    struct B : A {int anotherInt}; 
    A a; 
    B b; 
    
    /* Compiler thinks: B inherits from A, so I'm going to create
       a new A from b, stripping B-specific fields. Then, I assign it to a.
       Let's do this!
     */
    a = b;
    
    /* Compiler thinks: I'm missing some information here! If I create a new B
       from a, what do I put in b.anotherInt?
       Let's not do this!
     */
    b = a;
    

    In your example, there's no attributes someInt nor anotherInt, so it could work. But the compiler will not allow it anyway.

提交回复
热议问题