I am designing a system, I have not yet implemented first I am just diagraming it and then will code it, I want to ask one simple question:
What to do when we are using both inheritance and composition at the same time?
For example, in a hotel, there are 2 kinds of room standard room and Twin room let us say. For this I can use inheritance concept and these 2 kinds of rooms will be derived class but i can also use composition and will make seperate class for standard and twin room, then will use this is my hotel class.
What should I do?
This question is kinda vague and there are many details missing, yet I'll share some ideas...
First thing: while working on design of your application, what matters the most are the requirements.
You need to try to identify entities that will have some meaning in your system first. Let's say you know that there will be Hotel and Room. Note, that this relation is a composition already, mainly because:
in C++, composition usually means "by value", i.e. class Hotel
could have Room room;
that would be an object with automatic storage duration with its lifetime tied to the lifetime of instance of Hotel
, with multiple rooms you could just put them to the vector yielding the same relationship:
class Room { ... };
class Hotel {
public:
std::vector<Room> rooms;
};
(By the way, an aggregation would be most likely represented by a pointer or reference). This is another good example of composition:
If you know that there will be different kinds of rooms, first questions should be: will these objects have different behaviour? will my system treat them in different way? ...maybe you don't need to go for finer granularity than Room and everything that a concrete room will be specific with will be expressed with its attributes - size, number of beds, maybe dozens of boolean "has" flags ("has aircon", "has TV", "has microwave", ...), maybe all of its properties can be expressed with simple "type", values of which you would put into the enum
.