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

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

    Remember that if there's not an explicitly declared copy-assignment operators one will be implicitly declared and defined for any class (and structs are classes in C++).

    For struct A it'll have the following signature:

    A& A::operator=(const A&)
    

    And it simply performs memberwise assignment of its subobjects.

    a = b; is OK because B will match with the const A& parameter for A::operator=(const A&). Since only members of A are 'memberwise assigned' to the target, any members of B that aren't part of A get lost - this is known as 'slicing'.

    For struct B the implcit assignment operator will have the following signature:

    B& B::operator=(const B&)
    

    b = a; is not OK because A won't match the const B& argument.

提交回复
热议问题