🪤Go deeper — read the bookC++ Gotchas & Trick Questions— runnable code & full walkthrough →

oops · medium

Object Slicing

When a Derived object is copied into a Base by value, only the Base subobject is copied — the extra Derived members are 'sliced off', and Base's copy constructor sets the vptr to Base's vtable. Virtual calls on the slice therefore dispatch to Base, silently losing polymorphism. Binding a Base& or Base* to the object copies nothing and keeps the Derived vptr, so virtual dispatch still reaches Derived. Rule: handle polymorphic objects through references or pointers, not by value.

🔑 Key line

Object slicing: copying a Derived into a Base BY VALUE keeps only the Base subobject and resets the vptr to Base, so virtual calls lose polymorphism. Pass polymorphic types by reference or pointer.

The code

struct Base {
int id;
virtual void speak();
};
struct Derived : Base {
double extra;
void speak() override;
};
Derived d;
Base b = d; // BY VALUE: copies only the Base subobject
b.speak(); // -> Base::speak (Derived part is gone)
Base& r = d; // BY REFERENCE: no copy, full object
r.speak(); // -> Derived::speak (polymorphic)

What this lesson walks through

  1. 01
  2. 02
  3. 03
  4. 04
  5. 05
  6. 06

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Object Slicing and 100+ animated C++ interview lessons.

← Previous
Virtual Calls in Ctors & Dtors
Next →
Upcasting, Downcasting, dynamic_cast & RTTI