Pointer to array of base class, populate with derived class

前端 未结 5 372
心在旅途
心在旅途 2020-12-15 09:47

If I have a base class, with only virtual methods and 2 derived classes from the base class, with those virtual methods implemented.

How do I:

 // ca         


        
5条回答
  •  一整个雨季
    2020-12-15 10:09

    If your BaseClass contains pure virtual methods, this will fail to compile :

    BaseClass* base = new BaseClass[2];
    

    If it doesn't, you are going to get memory leak.

    In c++, this is done by using std::vector or std::array, with some kind of smart pointer. For example :

    std::vector< std::shared_ptr< BaseClass > > arr( 2 );
    arr[0].reset( new FirstDerivedClass() );
    arr[1].reset( new SecondDerivedClass() );
    

提交回复
热议问题