Home > Backend Development > C++ > How Does Object Slicing Affect Polymorphism in C ?

How Does Object Slicing Affect Polymorphism in C ?

Susan Sarandon
Release: 2024-12-17 11:20:27
Original
396 people have browsed it

How Does Object Slicing Affect Polymorphism in C  ?

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;
}
Copy after login

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();
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template