What is Object Slicing in C++ ?

0 votes
asked in Interview Question by nitin2604

In object oriented programming mainly in c++, there is a concept called “Object Slicing”.This question is asked in interviews either directly or indirectly.

Add question to:

1 Answer

+1 vote
answered by nitin2604
selected by admin
Best answer

Object Slicing is the object oriented programming concept mainly for C++. Object Slicing is mainly occur where you assign the object of derived/child class to object of base class which raises the condition of losing a part of information.

class Base{
   int foo;

class Derived : public Base {
   int bar;

int Random_Function(Base obj){

In the above example when you pass the derived object to the function, then “bar” member variable will be lost in this case. Only member variable which are present in base will be sliced in rest are sliced out. 

So, its called object slicing.

Check the below detailed example: 

Class Base
       int i;

class Derived : public Base
       int j;

int main()
   Base B;
   Derived D;
   B = D;    //only i is copied to B1

To overcome this problem the pointer and refrence are used.