#Polymorphism slicing

6 messages · Page 1 of 1 (latest)

crimson bough
#

I understand that poly morphism is just where the parent class is the interface and the behavior is defined by the derived class. So the proper way to do it is:

animal *a1 = new dog();
a1->speak();

And I understand that the following example is the wrong way to do it because of “slicing” and it will just call the animal speak:

animal a1 = dog();
a1->speak();

I’m just curious what is “slicing” and why does it do what it does? Aka what goes on in the background?

olive caveBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

hollow minnow
#

when you create an instance of animal, the compiler only allocates enough space for the base class - that instance is immutably an instance of the base class and only the base class. when you do animal a1 = dog() you're doing a copy-construction of an animal from a dog, and the resulting object is only an animal with none of the additional features of the derived class

hidden pecan
#

The problem is that a1 is an animal and cannot hold a dog.

#

Also, don't use new, not even for polymorphism. animal &&a1 = dog(); is so much better. Avoided dynamic memory, don't need delete, no -> to access stuff.

safe parrot
#

to clarify a little: technically, the overridden functions are stored in the virtual table and not inside the object instance itself (on GCC anyway) so the functions do not get sliced but rather the object's vptr is discarded and the vptr of the base class is assumed instead, since calling the overridden function could invoke out of bounds access if it requires one of the sliced members