Home > Backend Development > C++ > How Can I Avoid Object Slicing When Using Inheritance with C Vectors?

How Can I Avoid Object Slicing When Using Inheritance with C Vectors?

Susan Sarandon
Release: 2024-12-16 16:16:12
Original
793 people have browsed it

How Can I Avoid Object Slicing When Using Inheritance with C   Vectors?

Object Slicing and Polymorphism in Vector Containers

When dealing with inheritance in C , it is sometimes desirable to store instances of derived classes in containers such as vectors. However, the straightforward approach of using a vector to store base class objects can lead to object slicing, where derived class-specific data is lost.

Consider the following program:

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

The code creates a vector of Base objects and stores an instance of the Derived class. However, when calling the identify() method on the stored object, it prints "BASE" instead of "DERIVED." This is because object slicing occurs when the Derived object is assigned to the Base vector element, resulting in the loss of derived-specific data.

To prevent object slicing and preserve polymorphic behavior, the preferred solution is to use pointers to base class objects in the vector:

vector<Base*>
Copy after login

This ensures that the derived class-specific data remains intact. Additionally, to avoid manual memory management, smart pointers can be employed:

vector<std::shared_ptr<Base>>
Copy after login

Smart pointers ensure automatic memory management through RAII (Resource Acquisition Is Initialization), making it a more robust and C -conforming approach.

The above is the detailed content of How Can I Avoid Object Slicing When Using Inheritance with C Vectors?. 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