Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectors and polymorphism in C++

I have a tricky situation. Its simplified form is something like this

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

And then in one class I do something like...

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

And in yet another class...

void some_other_method()
{
    Instruction ins = v.back();
    ins.execute();
}

And they share this Instruction vector somehow. My concern is the part where I do "execute" function. Will it work? Will it retain its Add type?

like image 530
user44273 Avatar asked Apr 21 '13 00:04

user44273


1 Answers

No, it won't.

vector<Instruction> ins;

stores values, not references. This means that no matter how you but that Instruction object in there, it'll be copied at some point in the future.

Furthermore, since you're allocating with new, the above code leaks that object. If you want to do this properly, you'll have to do

vector<Instruction*> ins

Or, better yet:

vector< std::reference_wrapper<Instruction> > ins

I like this this blog post to explain reference_wrapper

This behavior is called object slicing.

like image 182
Daniel Gratzer Avatar answered Sep 28 '22 08:09

Daniel Gratzer