Forum Thread
  Posts  
C++ array with custom objects (Forums : Coding & Scripting : C++ array with custom objects) Post Reply
Thread Options
May 8 2019 Anchor

After searching google and stackoverflow for 2 days I haven't found anything yet

I was working with java about a year now and I decided to create a game on C++ for practice

In java this should work but in C++ it blows my mind.

I have this code

Item* inventory = new Item[24];

It's array (inventory) that holds Items

When I allocate dynamicly an array all of its postions are null? And if not, can I make them all null?

And thats the code for add an item at first empty position (pick up an item) kissanime

void Inventory::addItem(Item it){
    if(isFull()){
        cout << "Full inventory" << endl;
    }else{
        for(int i = 0; i<length; i++){
            if(inventory[i]== nullptr){ // need this to work somehow
                  inventory[i]= it;
            }
        }
    }
}

It needs to be array not a vector because it has fixed size

May 8 2019 Anchor

A full example

#include <iostream>
#include <stdio.h>
#include <memory.h>

using namespace std;

class Item
{
public:
    Item()
    {
    }

    explicit Item(int id)
    {
        this->id = id;
        cout << "Created item " << this->id << endl;
    }
    
    Item(const Item &item)
    {
        this->id = item.id;
    }
    
    virtual ~Item()
    {
        cout << "Deleted item " << this->id << endl;
    }
    
    int id;
};

#define MAX_ITEMS 10
class Inventory
{
public:
    Inventory()
    {
        memset(items, 0, sizeof(items)); // Clear array, set all elements to nullptr. <- optional, it is null by default.
    }
    
    virtual ~Inventory()
    {
        for (int i = (MAX_ITEMS - 1); i >= 0; --i)
            delete items[i];
    }
    
    bool isFull(void)
    {
        for (Item *it : items)
        {
            if (it == nullptr)
                return false;
        }
        return true;
    }
    
    void addItem(Item it)
    {
        if (isFull())
        {
            cout << "The inventory is full!" << endl;
            return;
        }
        
        for (int i = 0; i < MAX_ITEMS; i++)
        {
            if (items[i]== nullptr)
            {
                items[i]= new Item(it);
                break;
            }
        }
    }
    
    Item *items[MAX_ITEMS];
};

int main()
{
    Inventory *inv = new Inventory();
    
    inv->addItem(Item(33));
    inv->addItem(Item(2));
    
    for (Item *it : inv->items)
    {
        if (it == nullptr)
            cout << "This item is empty" << endl;
        else
            cout << "Found item " << it->id << endl;
    }
    
    delete inv;
    cout << endl << "DONE" << endl;
    return 0;
}


Reply to thread
click to sign in and post

Only registered members can share their thoughts. So come on! Join the community today (totally free - or sign in with your social account on the right) and join in the conversation.