Home > Backend Development > C++ > Can Vectors Hold Derived Class Objects Without Object Slicing?

Can Vectors Hold Derived Class Objects Without Object Slicing?

Susan Sarandon
Release: 2024-12-27 02:27:10
Original
496 people have browsed it

Can Vectors Hold Derived Class Objects Without Object Slicing?

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

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

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

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!

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