Array of base abstract class containing children class in C++

拟墨画扇 提交于 2019-12-02 09:00:34

Use the pointers and arrays of C++:

typedef std::array<std::unique_ptr<Top>,3> Tops;
Tops tops =
{{
    new MiddleA( "Kuku", 1337 ),
    new MiddleB( "Hoi", 42.0 ),
    new MiddleC()
}};

Only thing you have to have virtual destructor on your Top. Without virtual destructor you may only use shared_ptr, others will result with undefined behavior when objects are destroyed.

yes. You could do it this way.

Top* array[3] = { new Top(parms), new MiddleA(params), new MiddleB(params) };

but you will be only able to call GetName() function. You wouldnt be able to call other methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!