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;
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.