Home > Backend Development > C++ > body text

How Can Object Slicing Be Avoided When Working with Vectors of Inheritance Hierarchies in C ?

DDD
Release: 2024-11-01 09:00:03
Original
859 people have browsed it

How Can Object Slicing Be Avoided When Working with Vectors of Inheritance Hierarchies in C  ?

Vectors and Polymorphism in C : Object Slicing Unraveled

When dealing with vectors of inheritance hierarchies in C , one may encounter subtle intricacies that can impede intended behavior. Consider the following example:

<code class="cpp">class Instruction
{
public:
    virtual void execute() {  }
};

class Add: public Instruction
{
private:
    int a;
    int b;
    int c;
public:
    Add(int x, int y, int z) {a=x;b=y;c=z;}
    void execute() { a = b + c;  }
};</code>
Copy after login

Now, imagine storing an Add object in a vector of base class pointers:

<code class="cpp">void some_method()
{
    vector<Instruction*> v;
    Instruction* i = new Add(1,2,3)
    v.push_back(i);
}</code>
Copy after login

Later, in a separate method, we try to invoke the execute function on the last element of the vector:

<code class="cpp">void some_other_method()
{
    Instruction ins = v.back();
    ins.execute();
}</code>
Copy after login

A common misconception is that the execute function will behave as if called on an Add object. However, this is not the case.

The issue stems from the way vectors store values: they store copies of objects, not references. Therefore, when pushing the Add object into the vector, it gets copied, resulting in an object of type Instruction, losing the Add-specific data and methods. This is known as object slicing.

To avoid object slicing, we need to modify our vector to hold references instead of copies:

<code class="cpp">vector<Instruction*> ins</code>
Copy after login

Alternatively, we can use std::reference_wrapper:

<code class="cpp">vector< std::reference_wrapper<Instruction> > ins</code>
Copy after login

By using references, we retain the object's original type within the vector, allowing for polymorphic behavior as expected.

The above is the detailed content of How Can Object Slicing Be Avoided When Working with Vectors of Inheritance Hierarchies 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!