Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should this be called some special case of object slicing?

Tags:

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?

like image 329
jotik Avatar asked May 05 '16 12:05

jotik


People also ask

What do you mean by 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.

What is object slicing and how can we prevent it?

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.

What is object slicing in C++ with example?

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

How do you prevent object slicing in C++?

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.


1 Answers

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.

like image 164
John Zwinck Avatar answered Oct 19 '22 09:10

John Zwinck