Search code examples
c++oopmethodsencapsulationfriend

Encapsulation in a Composition Class C++


I have a map class, which contains a vector containing MapEntitys. MapEntity is a class of which Factory, Farm and 3 other classes are inherited from.

These 5 classes both should be "ticked" every few seconds, at which point they will all do a function individual to each class, but only the map class should be able to "tick" them.

How would I support this type of encapsulation in C++? Friends? Should I just use public methods and not misuse the methods? (Although I would prefer proper encapsulation for good practice, even though this code will not be re-distributed).


Solution

  • Syntactically you could use any of that.

    However, if MapEntities are to be "ticked" from outside, the tick method should be part of their public methods. Actually, it should be a virtual public method of the MapEntity class.

    And yes, public methods are proper encapsulation. They tell the user of your class what it can do. In this case, the user is the Map class and it can tick MapEntities.

    You should consider other solutions (friends, anonymous namespaces etc.) only if MapEntities are designed to be used only by Map.