What is object slicing? - C++

What is Object slicing? Give an example.

When a Derived Class object is assigned to Base class, the base class' contents in the derived object are copied to the base class leaving behind the derived class specific contents. This is referred as Object Slicing. That is, the base class object can access only the base class members. This also implies the separation of base class members from derived class members has happened.
class base
{
   public:
       int i, j;
};
class derived : public base
{
   public:
       int k;
};
int main()
{
   base b;
   derived d;
   b=d;
   return 0;
}
- Here b contains i and j where as d contains i, j& k. On assignment only i and j of the d get copied into i and j of b. k does not get copied. on the effect object d got sliced.

What is the object slicing?

In Inheritance, the attributes of the base class get carried to the derived class. However, we can assign a base class with the derived class without having the contents of the derived that are uncommon between then, copied to the base class.
Class B
{
   public:
       int i;
};

class D : public B
{
   public:
       int j;
};

int main()
{
   B B1;
   D D1;
   B1 = D1;    //only i is copied to B1
}
What is a data encapsulation?
What is a data encapsulation? - Data Encapsulation: The wrapping up of data and functions into a single unit (Class) is known as Encapsulation. .
What are Templates? - C++
What are Templates? - Templates enable us to define generic classes and generic functions. It can be considered as a kind of macro....
Describe DCOM infrastructure - C++
Describe DCOM infrastructure - It is an extension of COM. It allows network-based component interaction....
Post your comment
Discussion Board
Very well explained
Very well explained
Tushar 08-6-2016
object slicing
Very clear explaination about object slicing. Thankyou for this post.
poonam 07-23-2014