Search code examples
c++oopscopeclass-design

How do I share variables with another class in c++


I have two classes, Player and Controller. The Controller has the main game loop, and contains a Player. It also stores the world map. The Controller class passes user input to the player by calling various methods of the Player class, such as moveForward(). I am now implementing collision detection, and to do so, I need a way for the Player class to see the world map, but this is in the Controller class in which the Player class is.

In other words:

struct Controller {
    int worldMap[16][16][16];
    Player p;
    ...
}

struct Player {
    movePlayer() {
        #How do I check world map here?
    }
}

Solution

  • Pass the data that movePlayer() needs as a reference parameter:

    void movePlayer(const int (&map)[16][16][16]) { ... }
    

    Passing the whole Controller object would be bad if movePlayer() only needs access to worldMap.


    Alternatively, you could store a pointer to the current map in the Player object itself:

    struct Player {
        // ...
    
    private:
        int* Location;
    };