Home >Backend Development >C++ >Why Doesn\'t Polymorphism Work with a Vector of Instruction Objects in C ?
Vectors and Polymorphism in C
Polymorphism allows objects of different classes to share a common interface. In C , this is typically achieved through inheritance and virtual functions.
Consider the following code snippets:
<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>
Here, the Instruction class defines a virtual execute method, which is overridden in the Add class.
Now, let's create a vector containing Instruction objects:
<code class="cpp">vector<Instruction> v; Instruction* i = new Add(1,2,3); v.push_back(*i);</code>
In another method, we retrieve the last element of the vector and call its execute method:
<code class="cpp">Instruction ins = v.back(); ins.execute();</code>
Will it work?
No, it won't. The vector stores values, not references. This means that the Add object will be copied into the vector, resulting in object slicing.
How to fix it
To maintain polymorphism, we need to use a vector of pointers:
<code class="cpp">vector<Instruction*> v; v.push_back(i);</code>
Alternatively, we can use a vector of std::reference_wrapper
<code class="cpp">vector<std::reference_wrapper<Instruction>> v; v.push_back(i);</code>
This ensures that the objects are not sliced, allowing us to retain their dynamic types and call virtual functions correctly.
The above is the detailed content of Why Doesn\'t Polymorphism Work with a Vector of Instruction Objects in C ?. For more information, please follow other related articles on the PHP Chinese website!