Derived classes contain all information of their parent class,
and then some. Therefore
sizeof(Derived)
will always be >=
sizeof(Base)
.
A parent object ("bar" and "nah", in your example) only has
sizeof(Base)
bytes set aside for it in memory. This may not be large enough to hold all information necessary to represent a
Derived
object.
Therefore, if you attempt to assign a Derived to a Base object... you get what's called "object slicing", where the Derived-specific information of the object is "chopped off" because there isn't enough memory set aside in the Base object to contain all of it.
Creating the object with
new
sets aside as much space as is required for the object. A pointer to this set-aside space is then fed back.
A base pointer can safely point to this data because it is guaranteed to be at least big enough to have all the information required for a Base object. But it might
also have information in addition to that which is Derived specific.
EDIT:
Elaborating further:
This is a type error, because
Derived()
instantiates a temporary Derived object. You cannot assign an object to a pointer... they are fundamentally different types. A pointer is just an address whereas an object is the whole shebang.
This suffers from "object slicing". While syntactically legal... what's happening is you are creating a temporary Derived object, then assigning it to a Base object (bar).
In the process of assigning it, all Derived-specific information is "chopped off"/lost, and you're left with only the Base information (which is the only information 'bar' can hold... because it's a Base object and not a Derived object).
|
Base* meh = new Derived();
|
This is legal and correct.
new Derived();
creates a nameless Derived object somewhere in heap memory, then gives back a pointer to that memory. Since a Derived object also contains Base information, "meh" can safely point to that Base information. The fact that there may also be additional information besides that Base information does not change that.
|
Base nah = new Derived();
|
This again is a type error. The use of new here means you get a pointer back.. which you are trying to assign to an object.
EDIT: crap I so got ninja'd