tags:

views:

72

answers:

2

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 dont have to make seperate instances as a user. However, when I declare the board in my Puzzle.h file, it needs an actual number for the Board constructor.

i.e

/*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?

+6  A: 

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...
       {
       };
 };
Reed Copsey
Yup, that did it. I tried doing this at first without using an initialer list. Why would the initializer list make a difference? Thanks.
Isawpalmetto
All members need to be initialized directly when the constructor runs. You can use default initialization, but if you're not using a pointer, and there's no default constructor, you need an initializer list to construct those objects.
Reed Copsey
+1  A: 

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.

Matteo Italia