Home > Back-end >  How to reference a classes attribute inside another class method?
How to reference a classes attribute inside another class method?

Time:06-26

I'm trying to create a little ascii game where I can run around kill enemies etc. However I'm new to C and I would like to do something if the players location is at a certain point.

Below is a simpler version of the code and a picture of the problem:

#include <iostream>
using namespace std;

struct Game
{
    bool bGameOver = false;
    int iWidth = 20;
    int iHeight = 40;
    void Draw() {
        if (player.x == 5)
        {
            cout << "Hello"
        }
    }

};

struct Player
{
    bool bGameOver = false;
    int x = 0;
    int y = 0;

};

void Setup()
{

}

int main()
{
    Game game;
    Player player;
    while (!game.bGameOver)
    {
        Setup();
    }
}

Picture of the error

CodePudding user response:

The variable player is local in function main, so it's not visible where you tried to use it in Game::Draw.

One solution could be to make player a global variable. You'll need to switch the order of the structs:

struct Player
{
    bool bGameOver = false;
    int x = 0;
    int y = 0;

};

Player player;

struct Game
{
    bool bGameOver = false;
    int iWidth = 20;
    int iHeight = 40;
    void Draw() {
        if (player.x == 5)
        {
            cout << "Hello"
        }
    }

};

But I'd prefer to instead model things so a Game "has a" Player. So make Player a member of the Game:

struct Player
{
    bool bGameOver = false;
    int x = 0;
    int y = 0;

};

struct Game
{
    Player player;
    bool bGameOver = false;
    int iWidth = 20;
    int iHeight = 40;
    void Draw() {
        if (player.x == 5)
        {
            cout << "Hello"
        }
    }

};

(Aside: You probably don't want two different values called bGameOver, since keeping them in sync would be extra work. It sounds more like a game property than a player property to me.)

  • Related