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?

4

1 回答 1

4
Super mySuper = mySub;

在这种情况下,将实例化一个新对象并调用复制构造函数。新对象不包含任何额外内容是合理的。

Super& mySuper = mySub;

在这种情况下,您设置对对象的引用。引用就像一个指针,它不知道对象有多大。只有它引用了什么样的对象以及它在内存中的位置。基于从那个地址派生的“Sub”类mySuper可能与 的地址不同mySub。您可以通过使用指针并打印它们的值来轻松地尝试一下。虽然引用本身只知道对象的“超级”部分的位置,但您可以回退;编译器知道在哪里可以找到“Sub”对象的其余部分,如果它真的是一个的话。

于 2014-06-27T21:11:42.873 回答