Search code examples
c++polymorphismabstract-classdynamic-arrays

How using object pointer with dynamic array


Hello I'm studying c++ language and I'm really wondering that if use object Pointer with dynamic array. Weapon class is derived by CItem class. At this time I'm typing like this.

CItem* pItem = new cWeapon[m_size];

and I doing initialize each object like this

pItem[0].initialize();
pItem[1].initialize();
pItem[2].initialize();
pItem[3].initialize();
....
pItem[n].initialize();

However this time make problem. Size is different pItem and cWeapon. Because Pointer Operation cause error. and I wondering that how solve this problem?

sorry about my fool English skill.


Solution

  • Example code:

    #include <iostream>
    #include <memory>
    #include <vector>
    
    class BaseItem // abstract class
    {
    public:
        virtual void initialize() = 0; // pure virtual function (no implementation)
    };
    
    class Sword : public BaseItem
    {
    public:
        void initialize() override
        {
            std::cout << __PRETTY_FUNCTION__ << std::endl;
        }
    };
    
    class Shield : public BaseItem
    {
    public:
        void initialize() override
        {
            std::cout << __PRETTY_FUNCTION__ << std::endl;
        }
    };
    
    int main()
    {
        std::vector<std::unique_ptr<BaseItem>> items;
        items.emplace_back(new Sword);
        items.emplace_back(new Sword);
        items.emplace_back(new Shield);
        items.emplace_back(new Sword);
        items.emplace_back(new Shield);
    
        for(auto& element : items)
        {
            element->initialize();
        }
    
        return 0;
    }
    

    You can run it here: wandbox.org

    Output:

    virtual void Sword::initialize()
    virtual void Sword::initialize()
    virtual void Shield::initialize()
    virtual void Sword::initialize()
    virtual void Shield::initialize()
    

    In this implementation I used std::vector for dynamic arrays. Vector is containing types of smart pointer to BaseItem. In this case smart pointer is std::unique_ptr it helps a lot with resource management and it is easy to use. Without it you need manually delete all elements from vector. I really recomend using it.

    Our BaseItem now can provide "interface" that we want to implement in any other class. If you don't want to force class to implement such method just don't make it pure virtual (remove = 0 and add {} body of function)

    More information about:

    This is kind of "old" approach. You can read also about composition and entity system (ES).