There are 4 classes: A, B, C, and D. Class A “HAS A” B, and class C “HAS A” D. As it happens, C “IS A” A, and D “IS A” B. What’s the best way to model these relationships in C++?
The B that A has is the same D that C has.
Example: A building has an entrance, and a house has a door. A house is a building, and a door is an entrance.
I think there is a flaw in your design. If I understand correctly, you want to restrict the type of a base class member variable:
You could achieve that using accessors (getter/setter) to
entranceand checking the type, throwing an exception if the entrance is not a door, but that would break the Liskov substitution principle: you would not be able to manipulateHouses as if they wereBuildings:Some libraries perform this kind of restrictions (for example,
ReadOnlyCollection<T>throws an exception when one try to modify its content), but in my opinion, this is not a clean design. If collection’s interface states that I can add elements to the collection, then a read only collection is not a collection (since it does not support adding elements).The same reasoning can be applied here: a
Houseis not aBuildingsince it cannot contain all kind ofEntrances.