Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a pointer array of objects

Tags:

c++

So I have the following code

class UserDB
{
private:
AccountInfo* _accounts[200] ; // store up to 200 accounts
public:
UserDB();
virtual ~UserDB();
}
UserDB::UserDB(){
//code for initializing it to null
}
UserDB::~UserDB(){
    delete [] _accounts;
}

So basically I am trying to find this code to initialize _accounts to null but I cannot find a real answer, all the guides in the internet either say how to initialize an array, an object, or a pointer, but not something that is all three altogether, and even less how to initialize this kind of pointer to null, even whatever they are initializing [in the guides] looks very confusing, so I come once again to ask for help here. Also, AccountInfo is just any random class.

like image 547
Ren Avatar asked Mar 16 '26 00:03

Ren


1 Answers

use std::array or std::vector.

you don't delete[] _accounts because the array is a value -- it is an array of pointers. IOW, its size is not equal to a pointer.

Here's a std::vector approach:

class UserDB {
private:
    std::vector<AccountInfo*> _accounts;
public:
    UserDB() : _accounts(200, 0) {}
    virtual ~UserDB() {}
};

However, you may prefer to use the vector's default initializer so you can use it to determine the number of accounts it holds.

Update in response to comments below:

Although there are reasons to hold an array of AccountInfo* pointers, you may also consider std::vector to hold an array of AccountInfos values:

class UserDB {
private:
    std::vector<AccountInfo> _accounts;
public:
    UserDB() : _accounts() {}
    virtual ~UserDB() {}
    void appendAccountInfo(const AccountInfo& info) {
       this->_accounts.push_back(info);
    }
};

std::vector will handle all your allocation and reallocation needs for you. It's also nice because it's dynamically resizable, and you won't be constrained to a fixed number of AccountInfos.

like image 102
justin Avatar answered Mar 17 '26 18:03

justin