Home > Backend Development > C++ > Why Doesn\'t Polymorphism Work with a Vector of Instruction Objects in C ?

Why Doesn\'t Polymorphism Work with a Vector of Instruction Objects in C ?

Barbara Streisand
Release: 2024-11-02 14:41:29
Original
726 people have browsed it

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

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

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

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

Alternatively, we can use a vector of std::reference_wrapper:

<code class="cpp">vector<std::reference_wrapper<Instruction>> v;
v.push_back(i);</code>
Copy after login

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!

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