I have the following classes:
- Class called House (which have data regarding the house structure)
- Class called Room that is a composition of House.
So the problem comes when i want for example display the name of the house IN the room, so in order to do that i need to access House name from Room class which composition “has a” wont let me.
The workaround is to pass the house name by constructor to the room class, but that’s redundancy since i already have the data inside House class.
The other solution would be inherit House in Room which isn’t exactly “House IS A Room” and also i will loose the sugar syntax to make:
House.Room
So the question is: Is there are an standard workaround or re design pattern for this kind of problems?
Also here is an example:
class Room {
public:
MyHouseName(); //Needs access to const char* name from House
};
class House {
const char* name
vector<Room> rooms;
};
Luchian’s answer is right, but I see what you are thinking, so let me reinforce his answer. You want your House’s name accessible in a Room object, but a Room shouldn’t have a House reference, because a Room compose a House, and should not have any control on a House, right? Lets supose:
As you can see, you have access to the name of the House, and that’s ok, but you have also the power of demolish the house from a room! Ok, you know you shouldn’t use “m_myHouse->demolish()” inside Room class, but you can, and that’s a common mistake, providing more access to an object than the necessary. So the solution for this problem is use const methods and const objects. Let me show you:
Now, the “getName()” of House is const method, and that means that this method can be called from a const instance of House, because it doesn’t change the state of the object, you just read an information from House. And “demolish()” is not const, because it can change the state of a House (demolishing its rooms).
So, now we put a const reference of House in a Room, a “read-only” object. Now, Room doesn’t have the power to change the House anymore. You can’t call m_myHouse->demolish() in Room, you haven’t that control, but House can demolish any room. That’s how House “has a” Room.