views:

383

answers:

3

Here's a constructor for my Game class:

// Construct a Game to be played with player on a copy of the board b.
Game(const Board& b, Player* player)
{
  ...
}

Here's how I'm using the constructor:

Player p("Player Name");
Board b(6,3);
Game g(b, &p);

How does this work? Is b being copied?

If I want to save a pointer to player, should I create a private ivar like the following?

private:
  Player* _player;

...
// In Game constructor
_player = player;
+6  A: 

If you pass by reference or pointer then no copy is made. If you want to save a pointer, then yes, you need somewhere to save it.

Note that it is generally better practice to use constructor initialisation lists rather than assignment. prefer:

Game( const Board& b, Player * player ) : _player( player )
{
    // do something with Board
}

to:

Game( const Board& b, Player * player )
{
    _player = player;
    // do something with Board
}

For pointers, there is no great difference, but for more complex objects, using initialisation avoids possible semantic and performance problems with assignment.

anon
When assigning to constant members the initialization list is *the only* way.
Dario
+2  A: 

You are passing the board by reference, so no, it is not being copied.

If you have some code later like:

Board _privateBoard = b;

Then you are copying b. But it isn't getting copied into the function.

As for your question, yes you'll need to store the pointer somewhere if you want to get it back.

GMan
David Schmitt
Yup. I edited to clarify.
GMan
+4  A: 

As it was mentioned parameter won't be copied as it passed by reference.
But I'd like to point to some style issues.

Don't mix your style. Is it possible to play game without a player? If it is not, pass the player by the reference.

Another mix. One parameter you pass as the whole word and other as one letter.

Game(const Board& board, Player& player):
    _player(player)    
{
  ...
}

private:
  Player& _player;

And possibly you will want to store the Board too as it makes sense. Game can "know" about the board.

private:
    const Board& _board;

Then your constructor will be

Game(const Board& board, Player& player):
    _board(board),
    _player(player)
{
  ...
}
Mykola Golubyev
+1 for pointing out that no pointer is needed to avoid copying -- references can be used too.