Home >Backend Development >C++ >How Can Object Slicing Be Avoided When Storing Derived Class Objects in Base Class Vectors?
Object Slicing in Derived Class Storage
When storing objects of derived classes in vectors designed for base classes, one may encounter unexpected behavior. The reason lies in object slicing, where derived class-specific members are truncated.
Example:
#include <vector> using namespace std; class Base { public: virtual void identify() { cout << "BASE" << endl; } }; class Derived : public Base { public: virtual void identify() { cout << "DERIVED" << endl; } }; int main() { Derived derived; vector<Base> vect; vect.push_back(derived); // Object slicing occurs here vect[0].identify(); // Unexpectedly prints "BASE" return 0; }
Solution: Store Base Class Pointers with Smart Pointers
To avoid object slicing, store pointers to base class objects in the vector. Specifically, use smart pointers to manage memory effectively:
// Include smart pointer library #include <memory> // Replace raw pointers with smart pointers vector<shared_ptr<Base>> vect; int main() { Derived derived; vect.push_back(make_shared<Derived>(derived)); vect[0]->identify(); // Properly prints "DERIVED" return 0; }
By using smart pointers, you can maintain the polymorphism of derived objects while seamlessly managing memory without manual pointer manipulation.
The above is the detailed content of How Can Object Slicing Be Avoided When Storing Derived Class Objects in Base Class Vectors?. For more information, please follow other related articles on the PHP Chinese website!