Object slicing is a common issue in C++ that occurs when an object of a derived class is assigned to a variable of a base class type. This can lead to the loss of information specific to the derived class. Here’s how to detect and address object slicing bugs in your code.
Object slicing happens when a derived class object is passed to a function that accepts a base class object, resulting in the derived portion of the object being "sliced off." For example:
class Base {
public:
virtual void display() const { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
void display() const override { std::cout << "Derived" << std::endl; }
};
void func(Base b) {
b.display(); // Object slicing occurs here
}
int main() {
Derived d;
func(d); // When invoking func, Derived is sliced to Base
}
To prevent slicing, use pointers or references to base class objects instead of passing by value. This maintains the polymorphic behavior and avoids object slicing:
void func(Base& b) {
b.display(); // No slicing occurs
}
int main() {
Derived d;
func(d); // Passing by reference keeps the Derived class intact
}
To avoid object slicing:
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?