What is object slicing in C++?
#include <iostream>
struct Base {
virtual const char* who() const { return "Base"; }
};
struct Derived : Base {
int extra = 42;
const char* who() const override { return "Derived"; }
};
int main() {
Derived d;
Base sliced = d; // copies only the Base part
const Base& ref = d; // no copy
std::cout << sliced.who() << ' ' << ref.who() << '\n';
}
Output
Base Derived
Pass polymorphic objects by reference, pointer or smart pointer, and store pointers in containers (std::vector<std::unique_ptr<Base>>), not objects. See Polymorphism.
Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Build a BankAccount class |
| Calculate areas with polymorphism |
| Overload operators for a Money class |