Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variable within its definition?

This is probably a dumb question. I am trying to make a text-mud. I need each Room class to contain other Room classes that one can refer to when trying to move to them or get information from them. However, I can not do that because I obviously can not declare a class within its definition. So, how do I do this? Here's what I mean when I state I can not do it:

class Room {
    public:
        Room NorthRoom;
        Room EastRoom;
        Room SouthRoom;
        Room WestRoom;
};
like image 327
Reznor Avatar asked Jan 29 '26 06:01

Reznor


2 Answers

It's not possible to have a Room member variable. You could use a pointer or reference though.

class Room {
    public:
        Room* NorthRoom;
        Room* EastRoom;
        Room* SouthRoom;
        Room* WestRoom;
};
like image 92
kennytm Avatar answered Jan 31 '26 20:01

kennytm


I am sure not EVERY room has four children rooms, right? Otherwise the number of your rooms is infinity which is hard to handle in finite memory :-)

You might try

class Room {
    public:
        Room* NorthRoom;
        Room* EastRoom;
        Room* SouthRoom;
        Room* WestRoom;
};

Then you can have NULL pointers when a room doesn't have children.

like image 25
Philipp Avatar answered Jan 31 '26 20:01

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!