2 minute read

Introduction

Object slicing is a phenomenon that occurs in C++ when an object of a derived class is assigned to a variable of the base class. This results in the loss of the derived class’s specific characteristics, and only the base class’s characteristics are retained.

Concept

Object slicing occurs when an object of a derived class is assigned to a variable of the base class. This happens due to the fact that the base class variable can only hold the information that is defined in the base class and not the derived class.

Example

class Base {
public:
    int x;
};

class Derived: public Base {
public:
    int y;
};

int main() {
    Derived d;
    d.x = 5;
    d.y = 10;
    Base b = d;
    std::cout << b.x << std::endl; // Output: 5
    std::cout << b.y << std::endl; // Output: not possible as y is not a member of Base class
}

In this example, we have a base class Base with a member variable x, and a derived class Derived that inherits from Base and also has a member variable y. We create an object d of the class Derived and assign values to both x and y.

Then we create an object b of the class Base and assign d to it. Now, when we try to access the value of y using the object b, it will not be possible as y is not a member of the class Base. This is because object d is assigned to b and b can only access the members of the class Base and the members of class Derived are sliced off.

Conclusion

Object slicing is a phenomenon that occurs when an object of a derived class is assigned to a variable of the base class. It leads to the loss of the derived class’s specific characteristics. To avoid this, we can use pointers or references to the base class instead of objects. Understanding object slicing and how to avoid it is important when working with inheritance in C++.

One way to avoid object slicing is to use polymorphism by making the base class’s functions virtual. Another way is to use smart pointers such as std::shared_ptr or std::unique_ptr. Additionally, using copy constructors and assignment operators in the derived class can also prevent object slicing.

It’s also worth noting that object slicing can be desirable in some cases, for example when we want to remove the derived class’s specific functionality and only keep the base class’s functionality. However, in most cases, it’s important to be aware of object slicing and take steps to prevent it if necessary.