Home  >  Article  >  Backend Development  >  Does Object Slicing Occur When Using a `vector` in C ?

Does Object Slicing Occur When Using a `vector` in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 14:07:02829browse

Does Object Slicing Occur When Using a `vector` in C  ?

Vectors and Polymorphism in C : Object Slicing

Consider the following C code:

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

In a separate class:

<code class="cpp">void some_method() {
    vector<Instruction> v;
    Instruction* i = new Add(1,2,3)
    v.push_back(*i);
}</code>

And in another class:

<code class="cpp">void some_other_method() {
    Instruction ins = v.back();
    ins.execute();
}</code>

These classes share the Instruction vector. However, we encounter a concern regarding the execute function. Will it retain its Add type?

Unfortunately, it will not. vector stores values, not references. This means the Instruction object will be copied at some point, leading to a phenomenon called "object slicing."

To resolve this issue, consider using vector or, more effectively, vector< std::reference_wrapper >.

The above is the detailed content of Does Object Slicing Occur When Using a `vector` in C ?. 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
Previous article:How do you overload the `Next article:How do you overload the `