Programming Code Examples

What is Object Slicing in C++2 min read

Object Slicing

In inheritance we can assign a derived class object to a base class object. But, a base class object cannot be assigned to a derived class object. When a derived class object is assigned to a base class object, extra features provided by the derived class will not be available. Such phenomenon is called object slicing.

Following program demonstrates object slicing:

Output of the above program is as follows:

In the above program, when is called, even though class B has variable y, we were not able to access it; which is treated as object slicing.

Pointer to Derived Class

A base class pointer can point to a derived class object. But, a derived class pointer can never point to a base class object. Following program demonstrates object slicing using a base class pointer:

Output of the above program is as follows:

Take your time to comment on this article.

Add comment