C++ create array of objects (from different classe

2019-02-17 10:07发布

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...

标签: c++ class
3条回答
啃猪蹄的小仙女
2楼-- · 2019-02-17 11:06
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)

查看更多
疯言疯语
3楼-- · 2019-02-17 11:06

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.

查看更多
甜甜的少女心
4楼-- · 2019-02-17 11:06

If you can't use libraries you need an array of pointers like:

baseClass *array[123];
array[0] = new first();
array[1] = new second();

and no slicing will occur. (don't forget to delete everything)

查看更多
登录 后发表回答