Cant_Focus
Cant_Focus

Reputation: 17

How can i get a function from a different class to call an object declared in Main?

I am making a tictactoe game and would like the function for a player turn to access objects i declared in main and other functions how could i do that?

void Player1Turn::player1Turn() {

char num;
cin >> num;

if (num == '1')
{
    board[0][0] = { xo1 };
}

For example how could i get board to change the values of gameboard?

int main()
{

    Setup setup;
    Gameboard gameboard;
    Player1Turn player1turn;

    setup.setup();
    gameboard.printBoard();
    player1turn.player1Turn();

    return 0;
}

If this is not enough code I could provide more

Upvotes: 0

Views: 72

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51835

You could add a reference to the specific Gameboard as an argument to the player1Turn member function. So, assuming your Gameboard class has a board[][] member, it would look something like this:

void Player1Turn::player1Turn(Gameboard& gb)
{
    char num;
    cin >> num;

    if (num == '1')
    {
        gb.board[0][0] = { xo1 }; // Exact code will depend on your "Gameboard" definition.
    }
}

And your call from main would be like this:

int main()
{
    Setup setup;
    Gameboard gameboard;
    Player1Turn player1turn;

    setup.setup();
    gameboard.printBoard();
    player1turn.player1Turn(gameboard); // Argument is the Gameboard to work on.

    return 0;
}

There are many other ways to achieve this, though, but I can't really suggest anything more/better without more details of your various classes. Another way, as suggested in the comment by Nico Schertler, would be to have the reference to Gameboard as a "data" member in the Player1Turn class and pass the reference in its constructor.

Feel free to ask for further clarification and/or explanation.

PS: Your use of the three names, "Player1Turn" (for the class), "player1Turn" (for the member function) and "player1turn" (for the specific object in main) is extremely prone to typing errors! You should seriously consider a better naming scheme!!

Upvotes: 1

Related Questions