Consider these two Base and Derived classes:
class Base {
public:
virtual ~Base() {}
virtual void print() const { std::cout#include <iostream> << "base\n"; }
int x;
};
class Derived : public Base {
public:
virtual void print() const { std::cout#include <iostream> << "derived\n"; }
int y;
};The memory layout of a derived object is its base part, then its derived part:
Object slicing occurs when the derived part is cut off because the derived object is copied into a base object. b only gets the base part, 0x1000 to 0x100B, so y is dropped. b's vptr points to Base's functions instead of Derived's functions:
Derived d;
Base b = d; // Copies only x.
b.print(); // baseA reference or pointer to the base refers to the original object instead of copying it. The whole block of memory for the object is preserved. r and p both refer to 0x1000:
Base& r = d;
Base* p = &d;
r.print(); // derived
p->print(); // derivedWarning
Object slicing can occur when passing by value, returning by value, and storing the derived object in a container of base objects.
Note
Object slicing can be prevented by making the base class's copy constructor and copy assignment protected. Derived can still be copied, but Base b = d; no longer compiles.
References
- cppreference: derived classes
- C++ Core Guidelines C.67: A polymorphic class should suppress public copy/move
Dan