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:
Tutorials
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?