Let's say I have a class Derived
which derives from class Base
whereas sizeof(Derived) > sizeof(Base)
. Now, if one allocates an array of Derived
like this:
Base * myArray = new Derived[42];
and then attempts to access the n
-th object using
doSomethingWithBase(myArray[n]);
Then this is might likely (but not always) cause undefined behaviour due to accessing Base
from an invalid location.
What is the correct term for such an programming error? Should it be considered a case of object slicing?
Object slicing is used to describe the situation when you assign an object of a derived class to an instance of a base class. This causes a loss of methods and member variables for the derived class object. This is termed as information being sliced away.
Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object. We can avoid above unexpected behavior with the use of pointers or references.
"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away. For example, class A { int foo; }; class B : public A { int bar; }; So an object of type B has two data members, foo and bar .
Object slicing can be prevented by making the base class function pure virtual thereby disallowing object creation. It is not possible to create the object of a class that contains a pure virtual method.
It is not slicing at all, rather it is undefined behavior because you are accessing a Derived
object where none exists (unless you get lucky and the sizes line up, in which case it is still UB but might do something useful anyway).
It's a simple case of failed pointer arithmetic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With