Home > Backend Development > C++ > body text

Does Object Slicing Affect Polymorphism in C Vectors?

Patricia Arquette
Release: 2024-11-02 05:50:02
Original
759 people have browsed it

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

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

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

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

or

<code class="cpp">vector< std::reference_wrapper<Instruction> > ins;</code>
Copy after login

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!

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!