Object Slicing in C++

In this tutorial, we will learn about object slicing in the C++ programming language.

In C++ programming, Object Slicing is a process in which an object of a child class type is copied(assigned ) to an object of a parent class type.

Example:

class Parent 
{
public:
int a;
int b;
};
class Child : public Parent
{
public:
int p;
};
int main()
{
Child c;
Parent t=c;//here the object of child class is assigned to the  object of parent class i.e Object Slicing
return 0;
}

Explanation:

In the above code, Object of parent class t   contains a and b whereas Object of child class c contains a,b and p and

After assigning the object of derived into the object of the base class, only a and b of the derived class is copied into a and b of the base class.

Example:

#include<iostream>
using namespace std;
class Base
{
  int a;
  int b;
  public:
    Base(int p,int q)
    {
      a=p;
      b=q;
    }
    void display()
    {
      cout<<"a:"<<a<<endl;
      cout<<"b:"<<b<<endl;
    }
    
};
class Derived:public Base
{
  int c;
  public:
  Derived(int x,int y,int z):Base(x,y)
  {
    c=z;
  }
  void print()
  {
    display();
    cout<<"c:"<<c<<endl;
  }
};
int main()
{
  Derived d(10,20,30);
  Base b(100,200);
  b=d;
  b.display();
  d.print();
}

Output:

a:10
b:20
a:10
b:20
c:30

In the above example, the base class object slices off the attributes of the derived class object.

This is the property of object slicing.

Object slicing doesn’t occur because when functions use pointers or references as function arguments since pointers and reference any type take some amount of memory.

 

Object slicing doesn’t occur by making the base class function pure virtual thereby disallowing object creation.

If a class contains a pure virtual method, then it’s not possible to create an object.

Thus In C++, a derived class object can be copied to a base class object, Otherwise, it’s not possible.

you can read this topic:- Find smallest prime divisor of a number in C++

Leave a Reply

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