Max Payne
Max Payne

Reputation: 2438

Calling a function of another class from another class

I am working on a project where there are two player objects and one game object.

The two player objects need to access the game object's function display(), but i have no idea how this could be done.

Below is a snippet highlighting the core issue:

class Game 
{
public:
    Game() {}
    display() {...}
    ...
};

class Player 
{
public:
    Player() {}
    void input()
    {
        ...
        // display();
        ...
    }
};

Please suggest a way to solve this problem. if you find fundamental issue with this design pattern, feel free to correct that!

Upvotes: 0

Views: 83

Answers (1)

Ajay
Ajay

Reputation: 18441

Why not?

void input()
{
    game.Display();
}

but probably, you need to pass a Player object to it. Thus, change it this way:

class Player; // FORWARD declaration
class Game 
{
public:
    Game() {}
    void display(Player& player); // Implement elsewhere not here.

    // Another way
    void display(Player* player = NULL); // Implement elsewhere not here.
    ...
};
...
 void input()
    {
        game.Display(*this);
           game.Display(this); // another way
    }

Upvotes: 1

Related Questions