MiddleDebuggingCommonNot answered yet
What is object slicing and how do you prevent it?
Circle carries a radius, but after this code runs describe() prints the base-class shape and the radius is gone.
#include <iostream>
#include <vector>
struct Shape {
virtual void describe() const { std::cout << "Shape\n"; }
};
struct Circle : Shape {
double r = 1.0;
void describe() const override { std::cout << "Circle r=" << r << "\n"; }
};
int main() {
std::vector<Shape> shapes;
shapes.push_back(Circle{}); // stored as Shape by value
shapes[0].describe(); // prints "Shape", radius lost
}
Find and fix the bug.
Slicing occurs when a derived object is assigned or copied into a base by value, discarding all derived members. Prevent it via references, pointers, or smart pointers — or by deleting the base copy constructor.
- ✗Storing polymorphic objects in std::vector<Base> by value — each element is sliced on insertion
- ✗Passing a derived object to a function that accepts Base by value
- ✗Assigning a derived to a base variable without realising it compiles silently
- →Why does std::vector<Base> cause slicing?
- →How does deleting the copy constructor in an abstract base class prevent slicing?