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...
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With