1

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

1 Answer 1

2

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 )
{
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works great! Thanks for giving both examples. I'm still learning C++ and seeing both examples was excellent for learning. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.