Home  >  Article  >  Backend Development  >  Does Object Slicing Affect Polymorphism in C Vectors?

Does Object Slicing Affect Polymorphism in C Vectors?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 05:50:02760browse

Does Object Slicing Affect Polymorphism in C   Vectors?

Vectors and Polymorphism in C

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 store copies of Instruction references, not the references themselves. This means that when the Add object is pushed back into the vector, a copy of the reference is made.

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!

Statement:
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