Isawpalmetto
Isawpalmetto

Reputation: 795

Is it possible to have an instance of a class as a data member of another class?

I have a Board class where the constructor takes in the dimensions of the board as the parameter. I also have a Puzzle class that holds pieces and I want it to have a Board as a data member. I want it like this so that when I create an instance of Puzzle, I will have my instance of Board created as well so I don't have to make separate instances as a user. However, when I declare the board in my Puzzle.h file, it needs an actual number for the Board constructor:

// Puzzle.h file

private:
  Board theBoard(int height, int width); // Yells at me for not having numbers

Is there a way to have an object of a class be a data member for another class if that object hasn't been created yet?

Upvotes: 2

Views: 362

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126777

You have to declare the data member without specifying anything more than the type, and then initialize it with the special constructor initialization list syntax. An example will be much clearer:

class A
{
    int uselessInt;
  public:
    A(int UselessInt)
    {
        uselessInt=UselessInt;
    }
};

class B
{
    A myObject; //<-- here you specify just the type
    A myObject2;
  public:

    B(int AnotherInt) : myObject(AnotherInt/10), myObject2(AnotherInt/2) // <-- after the semicolon you put all the initializations for the data members
    {
        // ... do additional initialization stuff here ...
    }
};

Here you can find a detailed explanation.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564373

If I understand correctly, the problem is that you need to instantiate your board correctly:

 class Puzzle {
 public:
       Board theBoard;

       Puzzle(int height, int width) : theBoard(height, width) // Pass this into the constructor here...
       {
       };
 };

Upvotes: 6

Related Questions