Can Vector Hold Derived Class Objects as Base Class Variables?
In C , a perplexing issue arises when attempting to store objects of derived classes in vectors whose elements are of the base class type. Like in the provided example:
#include <iostream> #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); vect[0].identify(); return 0; }
Instead of printing "DERIVED" as expected due to virtual method dispatch, this code prints "BASE." This unusual behavior stems from object slicing.
The Culprit: Object Slicing
Object slicing refers to the loss of derived class-specific data when storing an instance of a derived class in a variable of the base class type. This is because the compiler only copies the shared portion of the objects, discarding the derived class-specific members.
An Alternative Way with Smart Pointers
To overcome object slicing and achieve polymorphic behavior, the best practice is to store pointers to base class objects in the vector. This eliminates slicing while preserving the dynamic nature of the derived class methods.
vector<Base*> vect; vect.push_back(&derived); // Store a pointer to the Derived object
The C Way: Using Smart Pointers
To enhance the object-oriented approach, it is recommended to use smart pointers instead of raw pointers. Smart pointers handle memory management automatically, ensuring safe and clean code.
#include <memory> vector<unique_ptr<Base>> vect; vect.push_back(make_unique<Derived>());
The above is the detailed content of Can Vectors Hold Derived Class Objects Without Object Slicing?. For more information, please follow other related articles on the PHP Chinese website!