-3
class element
{
public:
    element();
    virtual void foo() = 0;
};

class bar : public element
{
public:
    bar();
    void foo() override
    {
        // Stuff
    }
};

class baz : public element
{
public:
    bar();
    void foo() override
    {
        // Stuff
    }
};

I want to have instances of bar and instance of baz to be stored in the same vector or list.

vector<element> elements;
bar a = bar();
baz b = baz();

elements.push_back(a);
elements.push_back(b);

I know that the code above wont work but something with this kind of structure is what I am looking for.

I read somewhere that you can store a vector of unique_ptr< element> but I can't figure out how to turn instances of bar or baz into unique pointers of element.

Apologies if this is a duplicate, I tried looking for a solution but I couldn't find anything.

  • 1
    Do you know how to create *any* [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr) object? Start there, then think about how it would be stored in your vector. – Some programmer dude Aug 15 '16 at 11:22
  • Does [this](http://stackoverflow.com/questions/17417848/stdunique-ptr-with-derived-class) answer your question: – Wim Bokkers Aug 15 '16 at 11:27
  • I think that the main point you are missing here is how to use inheritance and polymorphism, e.g. the fact that you must use a pointer or reference to the base class to point/reference a derived class if you want a polymorphic handling. The detail of using `std::unique_ptr` here to hold the object comes only after the first point. – Yehezkel B. Aug 15 '16 at 13:56

1 Answers1

2

Use std::make_unique to create objects managed by unique_ptrs.

std::vector<std::unique_ptr<element>> vector; // Empty vector

vector.push_back(std::make_unique<bar>()); // Push a new bar
vector.push_back(std::make_unique<baz>()); // Push a new baz
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • What if I already have an instance of bar or baz. Do I have to create a new instance? – Conrad J Ludgate Aug 15 '16 at 11:46
  • @ConradJLudgate Yes. An instance can only exist in one place, so you have to copy (or move) it. `make_unique` forwards its arguments to the new instance's constructor, so you can use `std::make_unique(a)` to copy-construct the new `bar` from `a` (resp. `std::move(a)` to move-construct it). – Quentin Aug 15 '16 at 12:06