Pointer to array of base class, populate with derived class

前端 未结 5 371
心在旅途
心在旅途 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() );
    
    0 讨论(0)
  • 2020-12-15 10:09

    This was the answer (from Rubby)

    BaseClass* Base[2];
    
    Base[0] = new FirstDerivedClass;
    Base[1] = new SecondDerivedClass;
    
    0 讨论(0)
  • 2020-12-15 10:12

    It is C++ use std::vector instead of simple array:

    std::vector<BaseClass*> base;
    base.push_back(new FirstDerivedClass());
    base.push_back(new SecondDerivedClass());
    

    As Kerrek SB noticed safest method is to use std::unique_ptr:

    std::vector<std::unique_ptr<BaseClass> > base;
    base.push_back( std_unique_ptr<BaseClass>(new FirstDerivedClass()) );
    base.push_back( std_unique_ptr<BaseClass>(new SecondDerivedClass()) );
    
    0 讨论(0)
  • 2020-12-15 10:14

    Define a pointer array , the pointer type is BaseClass. And assign the pointer to the derivedclass to the elements of the array. just like:

    BaseClass* base [2];
    base[0] = new FirstDerivedClass;
    base[1] = new SecondDerivedClass;
    
    0 讨论(0)
  • 2020-12-15 10:18

    Your array is of the wrong type: it stores BaseClass object instances instead of pointers to them. Since BaseClass seems to be abstract, the compiler complains that it cannot default-construct instances to fill your array.

    Even if BaseClass were not abstract, using arrays polymorphically is a big no-no in C++ so you should do things differently in any case.

    Fix this by changing the code to:

    BaseClass** base = new BaseClass*[2];
    
    base[0] = new FirstDerivedClass;
    base[1] = new SecondDerivedClass;
    

    That said, most of the time it is preferable to use std::vector instead of plain arrays and smart pointers (such as std::shared_ptr) instead of dumb pointers. Using these tools instead of manually writing code will take care of a host of issues transparently at an extremely small runtime cost.

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