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

后端 未结 2 1437
旧时难觅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 06:05

    Use the pointers and arrays of C++:

    typedef std::array,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.

提交回复
热议问题