DERIVED OBJECT IN MEMORY:
┌───────────────────────────────────────┐
│ Base Data (x, y) | Derived Data (z, w)│
└───────────────────────────────────────┘
│
▼ (Passed by value: void func(Base b))
SLICED BASE OBJECT:
┌──────────────────┐
│ Base Data (x, y) │ ◄── Derived Data (z, w) is SLICED OFF and LOST!
└──────────────────┘Object Slicing in C++: Understanding Base-Class and Derived-Class Copies
Direct Answer & Core Concept
Detailed Explanation & Mechanics
1. Slicing Diagram:
2. Polymorphism Loss:
A sliced object has its vtable pointer reset to the base class vtable; all virtual function calls on it will invoke base class implementations.
Runnable Code Example: Object Slicing in C++
C++20 / C++23#include <iostream>
#include <string>
class BaseAnimal {
public:
virtual void speak() const {
std::cout << "[BaseAnimal] Generic sound\n";
}
};
class Dog : public BaseAnimal {
public:
void speak() const override {
std::cout << "[Dog] Woof Woof!\n";
}
};
// PROBLEM: Pass-by-value causes Object Slicing
void triggerSlicing(BaseAnimal animal) {
animal.speak(); // Sliced! Always calls BaseAnimal::speak()
}
// SOLUTION: Pass-by-reference preserves polymorphic identity
void preservePolymorphism(const BaseAnimal& animal) {
animal.speak(); // Calls Dog::speak() correctly
}
int main() {
Dog myDog;
std::cout << "Passing by Value (Object Slicing):\n";
triggerSlicing(myDog);
std::cout << "\nPassing by Reference (Preserved):\n";
preservePolymorphism(myDog);
return 0;
}