c++ - Why does slicing occur exactly? -


i understand slicing chops off additional sub class-specific parts of object, when assign super class sub class, so:

sub mysub; super mysuper = &mysub; // mysuper doesn't contain sub class behaviour 

and if did:

sub mysub; super& mysuper = &mysub; // mysuper contain sub class behaviour 

but don't understand why reference works , why object doesn't.

i have seen reason because without reference object needs copied- still don't see why should result in slicing?

i don't understand why reference works. pointing super reference beginning of sub object compiler knows how big super object should be, wouldn't expect associate memory beyond super part (corresponding sub class component of object) super reference?

super mysuper = mysub; 

in case new object instantiated , copy constructor called. reasonable new object not contain extras.

super& mysuper = mysub; 

in case set reference object. reference pointer , not know how big object is. kind of object references , lies in memory. based on classes "sub" derived address of mysuper might differ address of mysub. can try out using pointers , printing values. while reference knows location of "super" part of object, can cast back; compiler knows find rest of "sub" object, if one.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -