Difficulty: Intermediate
What is object slicing in C++? When does it happen and how can you prevent it?
Slicing is one of those bugs that makes polymorphism silently stop working, which is why interviewers use it as a trap after a virtual-function question. Let's see what is going on.
Imagine a layered cake. Suppose Derived is a Base cake with an extra frosting layer on top. If you cut a piece that contains only the Base layers and put it on a plate labelled Base, the frosting is gone, and you cannot get it back. Object slicing is exactly that: when you copy a Derived object into a Base object by value, only the Base part is copied. The Derived members are 'sliced off', and the resulting object is a genuine Base object, including its vptr, which points to Base's vtable. Therefore virtual calls on it resolve to Base's versions. There is no polymorphism because there is no longer a Derived.
Where does slicing occur in real code? Three usual places. First, direct assignment or initialisation: 'Base b = derived;'. Second, passing by value: 'void f(Base b)' called with a Derived argument. Third, and most damaging, storing objects by value in a container: 'std::vector<Base> v; v.push_back(Derived());'. That vector of Base cannot hold anything but Base objects, since each element is a Base-sized slot. Catching exceptions by value ('catch (Base e)') slices the exception too, which is why we catch by reference.
How do you prevent slicing? The simplest cure is to use references or pointers, which refer to the original object and leave the dynamic type intact: pass 'const Base&', hold 'std::vector<std::unique_ptr<Base>>' or a vector of reference wrappers. You can also make the base class abstract (with a pure virtual function), so it cannot be instantiated by value at all and the slicing copy won't compile. Another defensive option is to delete or protect the copy operations of the base class, and offer a virtual clone() method for explicit polymorphic copies (the prototype pattern).
Point out the difference between the pieces here: 'Base& r = d;' is fine and preserves polymorphism; 'Base b = d;' is the one that slices. Also assignment through references can produce a partial slice: 'Base& r1 = d1; Base& r2 = d2; r1 = r2;' copies only the Base subobject of d2 into d1, leaving d1 in a weird half-updated state.
Compilers rarely warn, so be conscious. In code reviews, look for polymorphic types passed by value, a vector of a base type, and catch clauses without ampersands. Static analyzers such as clang-tidy have a check (cppcoreguidelines-slicing) that flags these.
#include <iostream>
#include <memory>
#include <vector>
struct Base {
virtual ~Base() = default;
virtual const char* name() const { return "Base"; }
};
struct Derived : Base {
int extra = 42;
const char* name() const override { return "Derived"; }
};
void byValue(Base b) { std::cout << "byValue: " << b.name() << "\n"; }
void byRef(const Base& b) { std::cout << "byRef: " << b.name() << "\n"; }
int main() {
Derived d;
Base sliced = d; // copies only the Base part
Base& ref = d;
std::cout << sliced.name() << " " << ref.name() << "\n";
byValue(d);
byRef(d);
std::vector<Base> bad;
bad.push_back(d); // sliced
std::vector<std::unique_ptr<Base>> good;
good.push_back(std::make_unique<Derived>());
std::cout << bad[0].name() << " " << good[0]->name() << "\n";
}
Only reference or pointer access retains the dynamic type. Every by-value copy of d into a Base yields a real Base object.
object slicing, polymorphism, pass by value, containers