1

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?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user997112
  • 29,025
  • 43
  • 182
  • 361
  • 5
    _Slicing_ is a side effect of _copying_. Creating a reference doesn't copy the object. – Drew Dormann Jun 27 '14 at 21:06
  • 2
    `&mySub` ... is there a typo there? That's an address. – Drew Dormann Jun 27 '14 at 21:07
  • "We are pointing a Super reference to the beginning of a Sub object" - that is not true! (even if I replace reference with pointer) The pointer points to the beginning of the `Super` object contained in the `Sub` object. It is a huge difference when using multiple inheritance: the value of the pointer will depend on which base class you convert the object! – Csq Jun 27 '14 at 21:08
  • Is ["What is the Slicing Problem inC++"](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c?rq=1), (the top related article on this page), not descriptive enough for what causes slicing? – WhozCraig Jun 27 '14 at 21:32
  • @WhozCraig that is what I referred to by "I have seen the reason"- I dont want the reason, I want to understand why the reason it what it is. – user997112 Jun 27 '14 at 22:03

1 Answers1

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

ypnos
  • 50,202
  • 14
  • 95
  • 141