Best way to share a variable between classes

So I am learning about OOP and inheritance as I work on a programming project. Basically for one part of the project I have a set of bool variables that needs to be accessed by two separate classes. Since there is only a few variables is there any way of doing this without creating a third class to act as a base class so the other two classes can be a sub class of it just to share those few bool variables? The two classes are literally not related at all except for the fact that they need to share these bool variables. Thanks, any input will be great.

Design decisions like this are difficult to answer without knowing exactly what situation you have on your hands.

What are the two classes you have? What are the bools they need to share? In order to get good advice here, you'll need to be specific.
It is for a text based game project. One class is for the monsters, the other class if for the specific room you are in. If a monster is alive, its bool is assigned to 1. If it is dead, it becomes changed to 0. This bool is in the monster class, but I need the most efficient way for the room class to know this information. Is it just to make the room class a subclass of monsters?
Have you thought about using an interface?
This bool should be part of the Monster class. Whether or not the monster is alive is a clear property of that monster... so the monster should keep track of it.


If outside code (like the Room) needs to know if a monster is alive, it would need access to the monster object... then it can just call some kind of "isAlive()" member function to see whether or not the monster is still alive.

So yeah. No bools should be shared here. This can and should be done with clean encapsulation.

The next question to ask is.... does the room need to "own" the monsters? That is... can the monster move from one room to another?

If the monsters can only stay in one room, then it might be easiest to have the Room own the monsters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Monster
{
public:
    bool isAlive() { return alive; }

private:
    bool alive; // <- set to false when the monster dies
};


//...

class Room
{
private:
    std::vector<Monster>  monstersInThisRoom;
};
Topic archived. No new replies allowed.