Object Slicing in C++ with examples

Object Slicing :-

  • Object slicing occurs when a derived class object is assigned to a base class object
  •  when an instance of a derived class is copied to the base class object the additional attributes of a derived class object are sliced off to make the base class object
  •  which means that the share of members connected with the derived object will be lost (sliced off).
  • The base class object discards the data related to the derived class because the base class object does not contain information about the members derived.

Example:-

class Base
{
protected:
int j;
public:
Base(int k)
{ j = k; }
virtual void disp()
{
cout << "I am Base class object, j = " << j << endl; }
};

class Derived : public Base
{
int i;
public:
Derived(int b, int c) : Base(b) { i = c; }
virtual void disp()
{
cout << "I am Derived class object, j = "
<< j << ", i = " << i << endl;
}
}

void func (Base obj)
{
obj.disp();
}


int main()
{
Base b(10);
Derived d(20,30);
func(b);
func(d); // Object Slicing, the member i of d is sliced off
return 0;
}

After execution of above program you will get below output:-

  • We can avoid above the unpredictable behavior with the use of pointers or references.
    Object slicing This does not happen when the context or object of the objects is passed as pointer Or any type of reference takes the same amount of memory.
    For example, if we change the global method func () in the above method, then the object will not be slicing.

// rest of code is similar to above
void func (Base &obj)
{
obj.display();
}
// rest of code is similar to above

Example:-
#include <iostream>

using namespace std;

class Base
{
protected:
int j;
public:
Base(int k)
{ j = k; }
virtual void disp()
{
cout << "I am Base class object, j = " << j << endl; }
};

class Derived : public Base
{
int i;
public:
Derived(int b, int c) : Base(b) { i = c; }
virtual void disp()
{
cout << "I am Derived class object, j = "
<< j << ", i = " << i << endl; }
};

void func (Base &obj)
{
obj.disp();
}

int main()
{
Base b(10);
Derived d(20,30);
func(b);
func(d); // Object Slicing, the member i of d is sliced off
return 0;
}

Output:
I am Base class object, = 10
I am Derived class object, j = 30, i = 30

Leave a Reply

Your email address will not be published. Required fields are marked *