Freedom_Ben
Freedom_Ben

Reputation: 11923

How to initialize a pointer to an array as a member variable

I am trying to declare a member variable that is an array of unknown size, that contains pointers to objects (objects that don't have default constructors). Additionally, I want the array to be populated with NULL pointers until I explicitly assign it. How do I do this?

Here is what I have so far (unrelated code removed):

In the .h:

class Column
{
    private:

        Card  **_cards;
        qint32 _color;
};

In the .cpp:

Column::Column( qint32 color )
    :
_color( color )
{
    _cards = new Card[Card::maxValue()];
}

Here are the relevant compiler errors:

error: no matching function for call to ‘Card::Card()’
error: cannot convert ‘Card*’ to ‘Card**’ in assignment

Upvotes: 1

Views: 134

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

This is how you can do it:

class Column
{
    private:
        Card **_cards;
        qint32 _color;
};

Column::Column( qint32 color )
    : _cards(new Card *[Card::maxValue()])
      _color( color )
{
    for (size_t i=0; i!=Card::maxValue(); ++i) {
        _cards[i] = 0;
    }
}

but of course, using a std::vector would be better:

class Column
{
    private:
        std::vector<Card *> _cards;
        qint32 _color;
};

Column::Column( qint32 color )
    : _cards(Card::maxValue(),0)
      _color( color )
{
}

Upvotes: 2

Related Questions