Object Slicing

In C++, object slicing refers to a situation where you assign an object of a derived class to an object of its base class, resulting in the loss of derived class-specific information. This occurs when you assign or pass an object by value rather than by reference or pointer. Let’s illustrate this with an example:

#include <iostream>
using namespace std;

class Base {
public:
    virtual void print() {
        cout << "This is the Base class." << endl;
    }
};

class Derived : public Base {
public:
    void print() override {
        cout << "This is the Derived class." << endl;
    }
};

int main() {
    Derived derivedObj;
    Base baseObj = derivedObj;  // Object slicing occurs here

    baseObj.print();  // Outputs "This is the Base class."

    return 0;
}

In this example, we have a base class called Base and a derived class called Derived. The Base class has a virtual function print(), which is overridden in the Derived class.

Inside the main() function, we create an object of the Derived class named derivedObj. Then, we assign derivedObj to an object of the Base class named baseObj. This assignment leads to object slicing, where the derived class-specific information of derivedObj is sliced off, and only the base class portion remains in baseObj.

When we call the print() function on baseObj, it executes the base class’s implementation of the function and prints “This is the Base class.” This demonstrates that the overridden function in the derived class is not accessible through the base class object due to object slicing.

To avoid object slicing and preserve the derived class-specific information, you can use references or pointers instead of assigning objects by value.

Leave a Reply

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