Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ create array of objects (from different classes)

Tags:

c++

class

I need to create a array that holds objects from multiple classes.

Example

class baseClass
{
   //
};

class first : baseClass
{
   //
};

class second : baseClass
{
   //
};

How do I create array that can hold first and/or second object inside it?

It is somewhat of a home-task for me so I am forced to use arrays, I already searched and know that it is done with boost libraries ans such but I have no option here guys...

like image 960
Stan Avatar asked Oct 24 '11 15:10

Stan


2 Answers

The best practice for that would be to create an array of smart pointers - preferably either one of the Boost or C++11 versions - to the base class. Making it a pointer array eliminates the risk of "slicing" your objects when you access them. Using smart pointers reduces the risk of memory leaks. Making it a base class pointer means that either derived class can be stored there safely.

like image 67
Harper Shelby Avatar answered Sep 23 '22 17:09

Harper Shelby


baseClass *array[10];
baseClass **array2 = new baseClass *[size];

This is the simplest and most dangerous way. You have to be careful about the lifetime of the objects in order to avoid leaking or double freeing. You also have to be careful with the array's allocation and deallocation, especially if you have to change the size at runtime.

std::vector<baseClass*> vec;

This improves the previous example because the vector handles the memory of the array for you, but you still have to be careful with the baseClass pointers.

std::vector<boost::variant<first,second> > vec2;

This is another improvement that eliminates the need to manually allocate or deallocate memory for the objects, and it's type safe in terms of accessing the objects as firsts or seconds. You can't mistake one kind of object for another.

std::vector<std::unique_ptr<baseClass>> vec3;

With this option you can still confuse objects of different types for each other, but it uses only the standard library and you still don't have to manage the lifetime of the objects you allocate. It does use C++11 though.

Also, if you don't need a dynamic array you can use std::array<...,size>

std::array<std::unique_ptr<baseClass>,10> array3; has absolutely zero space or time overhead at runtime over baseClass *array[10];, and is much safer. (zero overhead, assuming a decent implementation)

like image 32
bames53 Avatar answered Sep 25 '22 17:09

bames53