Home > Article > Backend Development > Does Object Slicing Affect Polymorphism in C Vectors?
Problem:
Consider the following C code snippet:
<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>
A vector of Instruction references is created, and an Add object is added to the vector by pushing back its dereferenced value:
<code class="cpp">vector<Instruction> v; Instruction* i = new Add(1,2,3); v.push_back(*i);</code>
In another class, the last element of the vector is retrieved and the execute method is called:
<code class="cpp">Instruction ins = v.back(); ins.execute();</code>
Question:
Will the execute method retain its Add type, and will the code execute correctly?
Answer:
No, it will not.
The vector
Furthermore, the new operator is used to allocate memory for the Add object. However, since the object is not deleted, a memory leak occurs.
To correctly implement this scenario, one should use a vector of Instruction* or std::reference_wrapper
<code class="cpp">vector<Instruction*> ins;</code>
or
<code class="cpp">vector< std::reference_wrapper<Instruction> > ins;</code>
Additional Note:
The behavior described in this problem is known as object slicing.
The above is the detailed content of Does Object Slicing Affect Polymorphism in C Vectors?. For more information, please follow other related articles on the PHP Chinese website!