Home > Article > Backend Development > 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>
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>
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>
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>
Alternatively, we can use std::reference_wrapper:
<code class="cpp">vector< std::reference_wrapper<Instruction> > ins</code>
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!