Please consider the following code:
Base b;
if (something)
b = DerivedA();
else
b = DerivedB();
It's well known that in such a case, 'slicing' occurs: In C++ we can't assign a variable of a base type an object of the derived type; the object would be 'sliced' off anything that isn't defined in the base type. (If we want to do such a thing, we have to use pointers or references).
I want to understand the actual reason for this. I.e., the reason why a Base
variable can't hold a Derived
object without slicing it.
My assumption is that the reason for this is that a Base
object and a Derived
object might not be of the same size, thus we can't make guarantees on being able to store an entire Derived
object in a Base
variable. A Base
might take up 4 bytes, while a Derived
is 7 bytes. So we settle to always slicing the derived object to fit the size of the base type.
We are able to do this with pointers, because they all occupy the same amount of memory.
Is this assumption correct? If not, what is the actual reason for slicing?