Object Slicing in Polymorphism: Storing Derived Class Objects in Base Class Variables
When working with inheritance in C , one may encounter the issue of object slicing. This occurs when an object of a derived class is assigned to a base class variable, causing the derived class-specific members to be lost.
Consider the following example:
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; }
In this code, we expect the identify() method to print "DERIVED" since it's a virtual method. However, it prints "BASE" instead. This is because the derived object is sliced when stored in the vect vector, which is declared to hold Base objects.
To solve this issue and maintain polymorphic behavior, one must store a pointer to the base class in the vector instead of the object itself:
vector<Base*> vect; vect.push_back(&derived); vect[0]->identify();
Now, vect[0] points to a Derived object, ensuring that the identify() method of the derived class is called and prints "DERIVED".
To further enhance this approach and avoid manual memory management, smart pointers can be used. For example:
vector<unique_ptr<Base>> vect; vect.push_back(make_unique<Derived>()); vect[0]->identify();
This approach ensures that the memory for the Derived object is automatically managed, making the code more efficient and less error-prone.
The above is the detailed content of How Does Object Slicing Affect Polymorphism in C ?. For more information, please follow other related articles on the PHP Chinese website!