Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-01 14:07:02
Original
828 people have browsed it

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

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

And in another class:

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

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!

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!