Object Slicing in C++: Understanding Base-Class and Derived-Class Copies
What is Object Slicing in C++: Understanding Base-Class and Derived-Class Copies? Object slicing occurs when a derived class object is assigned or passed by value to a base class object. The compiler copies only the base class portion of the...
What is object slicing in C++, why does it occur during pass-by-value, and how is it prevented?
Explanation & In-Depth Details
```text
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!
└──────────────────┘
```
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.
Code Example
#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;
}Interview Question & Tips
A: Make base class copy constructors and assignment operators `protected` or `delete` them, forcing consumers to interact exclusively through references and pointers.
Q: Does object slicing occur with pointer assignments (`Base* b = new Derived()`)?
A: No. Pointers and references point to the full object in memory without copying or truncating member data.
Best Practices
• Delete or protect copy operations on polymorphic base classes to prevent accidental slicing.
• Use smart pointers (`std::unique_ptr<Base>`) for polymorphic container storage.
This study reference for Object Slicing in C++: Understanding Base-Class and Derived-Class Copies is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: