John
John

Reputation: 43

Can I initialize a class in another class?

I am working on a scrabble project. In the project I have a class for tiles that contains an int value for both the score of the letter and for the count of the tiles there are in the game. This is the _tile class.

The other class in my code is the tile_pool class. It is supposed to have 27 tile classes for the 26 letters and the blank tile. Unfortunately when I compile my code, I always get the "error: expected identifier before numeric constant".

class Tile {
    int count;
    int score;
    public:
    _tile(int , int );
};

_tile::_tile(int _count = 0, int _score = 0): count(_count) , score(_score) {
}

class Pool{
    Tile A(9,1); 
    ... (the rest of the letters)
};

I looked around and found Initialize a class object inside the other class constructor so I tried making a default constructor for the _tile object but that didn't change the error. I also found that when I take line 14 and put it in my main function, there are no issues. I also tried initializing the Tile first and then having a set_values function to set the count and score for a tile, but that didn't work either.

void set_values(int _count, int _score) {
    count = _count;
    score = _score;
}

And in the tile_pool function:

Tile A;
A.set_values(9,1);

That returned the "error: ‘A’ does not name a type"

I don't understand why I can't initialize a Tile in my tile_pool class but I can in my main. Any help is appreciated! Thanks.

Edit: Thanks for the answers! I edited the code to follow guidelines better and changed the way I declared my classes as suggested. I also changed my solution to:

class Pool {
    Tile a = Tile(9,1);
};

Upvotes: 4

Views: 9672

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

You could use member initializer list:

class Pool {
    Tile A; 
public:
    Pool() : A(9, 1) {}
};

Upvotes: 3

M.M
M.M

Reputation: 141554

The right syntax is:

Tile A = Tile(9,1);

or

Tile A{9, 1};

You probably want these to be static const because you only need one master tile for all instances of the class. (In fact this is a bad design entirely but you'll figure that out for yourself after a while).


BTW typedef class... is poor style, you should just write class Tile (or whatever you want to call your class). There is no need to have 2 names for the same class. Also, it is unconventional to use leading underscore (_tile) in a class name.

Upvotes: 2

Related Questions