What Is Object Slicing?
When a derived class object is assigned to a base class object by value (not by pointer or reference), only the base class portion is copied, and the extra members in the derived class are sliced off.
Example
#include <iostream>
using namespace std;
class Base {
public:
int a = 1;
virtual void show() {
cout << "Base: a = " << a << endl;
}
};
class Derived : public Base {
public:
int b = 2;
void show() override {
cout << "Derived: a = " << a << ", b = " << b << endl;
}
};
int main() {
Derived d;
Base b = d; // Object slicing happens here
b.show(); // Calls Base::show(), not Derived::show()
}
Output:
Base: a = 1
Correct Way (Avoid Slicing)
Use pointer or references
to handle polymorphism:
Base* bptr = new Derived();
bptr->show(); // Correctly calls Derived::show()
delete bptr;