Making a vector of instances of different subclasses

前端 未结 4 921
猫巷女王i
猫巷女王i 2020-12-06 14:17

Tried searching, nothing returns( i ithink).

Is it possible to make a vector of an abstract class?

For example, I have the super class Unit.

And I Ha

4条回答
  •  盖世英雄少女心
    2020-12-06 14:28

    Yes, but you'll need to use either pointers or smart pointers (I'd go with this).

    struct X
    {
        virtual ~X() {}  //<--- as pointed out in the comments
                         // a virtual destructor is required
                         // for correct deletion
        virtual void foo() = 0;
    };
    struct Y : X
    {
        virtual void foo() { }
    };
    
    int main()
    {
        std::vector a;
        a.push_back(new Y);
        a[0]->foo();
        for ( int i = 0 ; i < a.size() ; i++ )
            delete a[i];
        return 0;
    }
    

    Don't forget to delete the allocated memory.

    Why you can't use actual objects:

    Assume std::vector. This is illegal because:

    1. If you want to initialize your vector with some number of elements, the allocation would fail. A vector stores objects internally in continuous memory. A preallocation would fail because it would mean it needed to create objects, which can't be done for abstract classes.

    2. Even if you could, or the base class wasn't abstract, it wouldn't help too much, as you'd suffer from object slicing.

提交回复
热议问题