Object slicing — when a derived object is copied to a base object, derived parts are lost.
1class Base {2public:3 int x;4 virtual void print() { std::cout << "Base: " << x << "\n"; }5};67class Derived : public Base {8public:9 int y;10 void print() override { std::cout << "Derived: " << x << ", " << y << "\n"; }11};1213Derived d;14d.x = 1; d.y = 2;1516// Object slicing!17Base b = d; // b.x = 1, but y is lost18b.print(); // "Base: 1" — virtual dispatch lost!1920// Prevent with pointers/references21Base* bp = &d; // No slicing22bp->print(); // "Derived: 1, 2"2324Base& br = d; // No slicing25br.print(); // "Derived: 1, 2"2627// Prevent with = delete28Base& operator=(const Base&) = delete;
Prevention: