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

后端 未结 2 1438
旧时难觅i
旧时难觅i 2021-01-26 05:19

so I have a Top class, let say:

//Top.h
#pragma once
#include 
using std::string;

class Top
{
    protected:
        string name;
    public:
             


        
相关标签:
2条回答
  • 2021-01-26 05:52

    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.

    0 讨论(0)
  • 2021-01-26 06:05

    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.

    0 讨论(0)
提交回复
热议问题