Objects in objects

What is the correct way of making objects that contain objects.

I'll give an example. A house has rooms. A room has walls. A wall has a color.

I might want to make a house and add rooms to it. Then I wanted to set the colors of its walls. This must be common structure in software but I can't find any information. I guess I'm using the wrong search terms.

Basically my question is that should the house object contain the room objects which in turn contain the wall objects or should they all be on their own and have a reference to their owner object?

I think that the house class could have a map for rooms. The room class would also have a map for walls. Then the operation might be done like this:

 
house.rooms["kitchen"].walls["south"].setColor("red");
Last edited on
If, in your model (your mental picture), one object contains an object, then do that. Create your classes to reflect that model.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class wall
{
  colour thisWallsColour;
};

class room
{
  vector<wall> thisRoomsWalls;
};

class house
{
  vector<room> thisHousesRooms;
};

int main()
{
  house a_house;
}



The house object contains room objects.
Each room object contains wall objects.
Each wall object has a colour.

You could use a map rather than a vector, although I think I'd prefer all the information about a given object to be part of that object. If a room is named "kitchen" then that information should be part of the room itself.

1
2
3
4
5
class room
{
  string name;
  vector<wall> thisRoomsWalls;
};

Last edited on
If I used vectors instead of maps I would need to know the index of the room and wall I’d like to access.
Last edited on
Topic archived. No new replies allowed.