halbrd
halbrd

Reputation: 135

Instantiating object as a class attribute with custom constructor (C++)

I'm writing a standard game of Battleship using C++, with a Game object that contains two Player objects within it. When I try to instantiate the Player objects in the Game constructor, IntelliSense gives me two errors:

IntelliSense: expression must be a modifiable lvalue

IntelliSense: no suitable constructor exists to convert from "Player ()" to "Player"

Here's my header file:

class Player {
public:
    Player(string name);
    //More unrelated stuff (Get/Set methods and Attributes)
};


class Game {
public:
    Game(bool twoPlayer, string Player1Name, string Player2Name);
    //Get and Set methods (not included)
    //Attributes:
    Player Player1();
    Player Player2();
    int turn;
};

My definition of the Player constructor:

Player::Player(string name)
{
    SetName(name);
    //Initialize other variables that don't take input
{

And the code that's giving the errors:

//Game constructor
Game::Game(bool twoPlayer, string Player1Name, string Player2Name)
{
    Player1 = Player(Player1Name);  //These two lines give the first error
    Player2 = Player(Player2Name);
    turn = 1;
}

//Game class Gets
int Game::GetTurn() { return turn; }
Player Game::GetPlayer1() { return Player1; }  //These two lines give the second error
Player Game::GetPlayer2() { return Player2; }

What am I doing wrong? I've tried changing

Player1 = Player(Player1Name);
Player2 = Player(Player2Name);

to

Player1 Player(Player1Name);
Player2 Player(Player2Name);

and a number of other things, but nothing works. Thanks a lot in advance!

Upvotes: 3

Views: 7587

Answers (2)

Mateusz Grzejek
Mateusz Grzejek

Reputation: 12068

Player1 and Player2 are functions. I assume, that you wanted them to be a member variables.

Change Game definition to:

class Game
{
public:
    Game(bool twoPlayer, string Player1Name, string Player2Name);

    //Get and Set methods (not included)

    //Attributes:
    Player Player1;
    Player Player2;
    int turn;
};

And use initialization list to initialize your members:

Game::Game(bool twoPlayer, string Player1Name, string Player2Name)
: Player1(Player1Name)
, Player2(Player2Name)
, turn(1)
{
}

Read more about why you should initialize your members:

Now, these two lines:

Player Game::GetPlayer1() { return Player1; }
Player Game::GetPlayer2() { return Player2; }

will not generate any errors anymore.

Upvotes: 5

Grégory Vaumourin
Grégory Vaumourin

Reputation: 312

The problem seems to be in the class Game in your header file :

class Game {
public:
    Game(bool twoPlayer, string Player1Name, string Player2Name);
    //Get and Set methods (not included)
    //Attributes:
    Player Player1;// 
    Player Player2;//  
    int turn;
}; 

Remove the parenthesis when declaring your members otherwise you're creating functions called Player1 and Player2 that take no argument

Upvotes: 2

Related Questions