Cem Aytekin
Cem Aytekin

Reputation: 109

Sharing the object with an another class c++

I have two classes: a board class and a player class.Board needs to be shared among players.I get error in the player cpp file saying " 'Player::board' : must be initialized in constructor base/member initializer list"

Here is my player header file:

class Player {
private:
    Board &board;
    string name;  // I put a reference
};

in the player cpp file :

// I pass the board in the board class by refrence but get the above error
Player::Player(string n,Board&b) {   
    name=n;
    board=b;
}

Meanwhile my board class looks like that:

class Board {
private:
    int** board;
    int row;
    int column;
};

Board::Board(int r,int c)  {
    row=r;
    column=c;
    board=new value*[r];

    for(int i=0;i<r;i++) {
        board[i] = new value[c];
    }
}

Upvotes: 2

Views: 174

Answers (2)

erol yeniaras
erol yeniaras

Reputation: 3795

Try to avoid using references as class data members. Some common problems:

  • You have to initialize the reference in every constructor initilization list,
  • Semantics might be confusing,
  • References are perfect for passing parameters to methods,
  • References do not allow assignment

instead try to use pointers as data members, which will avoid the problems and your code will be more readable.

EDIT: If you need a single Board object to be shared among all players then you may use Singleton.

Upvotes: 1

vsoftco
vsoftco

Reputation: 56557

You cannot defer initializing a reference. As the error tells you, you need to initialize it in the member init list, like:

Player::Player(string n,Board&b) : board(b) // preferably also ,name(n)
{
    // rest of implementation
}

Preferably, you should also initialize name in the member init list, and pass the string n by const reference, like const string& n, so you avoid an extra copy. If you use g++, you can use the -Weffc++ compiler flag which will give you warnings about member list initialization etc.

Upvotes: 3

Related Questions