Reputation: 30615
I understand slicing chops off the additional sub class-specific parts of an object, when we assign a super class to a sub class, like so:
Sub mySub;
Super mySuper = &mySub;
// mySuper DOESN'T contain any sub class behaviour
and if we did:
Sub mySub;
Super& mySuper = &mySub;
// mySuper DOES contain the sub class behaviour
but I don't understand why the reference works and why the object doesn't.
I have seen the reason is because without a reference the object needs to be copied- but I still don't see why this should result in the slicing?
I also don't understand why the reference works. We are pointing a Super reference to the beginning of a Sub object but the compiler knows how big a super object should be, so I wouldn't expect to associate the memory beyond the Super part (corresponding to the sub class component of the object) to the Super reference?
Upvotes: 1
Views: 115
Reputation: 52357
Super mySuper = mySub;
In this case a new object is instantiated and the copy constructor is called. It is only reasonable that the new object does not contain any extras.
Super& mySuper = mySub;
In this case you set a reference to the object. A reference is like a pointer and it does not know how big the object is. Only what kind of object it references to and where it lies in memory. Based on what classes "Sub" is derived from that address of mySuper
might differ from the address of mySub
. You can easily try that out by using pointers and printing their values.
While the reference itself only knows the location of the "Super" part of the object, you can cast back; the compiler knows where to find the rest of the "Sub" object, if it really is one.
Upvotes: 4