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...
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.
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.
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.
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 overbaseClass *array[10];
, and is much safer. (zero overhead, assuming a decent implementation)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.
If you can't use libraries you need an array of pointers like:
and no slicing will occur. (don't forget to
delete
everything)