Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a data member vector of polymorphic objects on the heap?

I have an inheritance hierarchy where A is an abstract base class and B and C are polymorphic children.

I wish to have a vector class data member, on the heap, which can contain B and C objects.

So in the header file I have my

vector<A*> polymorphicobjs;

and in the constructor I tried to do:

polymorphicobjs = new vector<A>();

but obviously this wouldn't work. How do I achieve this?

like image 345
mezamorphic Avatar asked Sep 06 '25 03:09

mezamorphic


1 Answers

You shouldn't worry about keeping a std::vector of raw pointers. It will create a lot of hassles for you later on making sure you delete objects at the right time. What you should do is store a container of "managed" polymorphic objects (using smart pointers). Declare your vector:

std::vector<std::unique_ptr<A>> polymorphicobjs;

And now you can store polymorphic objects in the vector pretty easily (where B is a subclass of A):

polymorphicobjs.push_back(std::unique_ptr<B>(new B));

With this, you don't need to ever worry about calling delete on the objects in your vector. As soon as you "let go" of the vector (eg, when it goes out of scope in your function or it's automatically destructed if it's a class member), the objects will be deleted. The vector uniquely owns the objects.

But I need to share the objects with other code?!

If that's the case, then std::unique_ptr isn't the right choice. We can express that the objects are shared by using std::shared_ptr:

std::vector<std::shared_ptr<A>> polymorphicobjs;
// [...]
polymorphicobjs.push_back(std::make_shared<B>());

Why does the push_back look different for unique and shared?

Because C++14 isn't out yet. If you're lucky enough to use a new enough compiler (bleeding edge clang/gcc/VS2013), the unique version will look very similar:

// C++14
std::vector<std::unique_ptr<A>> polymorphicobjs;
// [...]
polymorphicobjs.push_back(std::make_unique<B>());
like image 183
Bret Kuhns Avatar answered Sep 07 '25 21:09

Bret Kuhns