Sunday 16 June 2019

What I learned about inheritance today

Working on the game object class hierarchy I was confronted with a problem that I had not been able to solve - until now. The solution is I guess kind of hack, but I think it's only fitting. So when you inherit from another branch of class(es) the "main" branch can't use the class in that other branch without virtual functions defined in the base class. These functions can use either components which is a common way to use classes when you are not sure about inheritance, or derived classes, both using function wrappers which is bad, because it can generate duplicate or similar code.

My solution is a virtual function in the base class that returns the slice of the derived class from another inheritance hierarchy. The base class obviously returns zero for non-existing slice, but any derived class can return the proper part of it simply with return this. Slicing doesn't matter when you return pointers, it just works. When the sliced class is abstract enough it doesn't cause problems with decoupling it from the host class. Real life examples are things like the opener part of an object such as door. It can have status (open, closed, etc.) and lock data as in case of this game, and another example is the actual container in objects that can contain items. Both "slices" are abstract in the sense that they don't need information about the host object when they are used. The routines that use them can have the host object pointer as well and it's the case here, because you may need to do things to base class object as well like change the graphics frame when door is opened or closed.

The reason for all this is remove "empty" virtual functions and functionality from base classes and other classes in the hierarchy that are not using some derived class functionality. With this new way to handle some aspects of game objects I can split the main hierarchy to object types that use only the functions they have and it's possible without writing multiple wrapper functions to each class, because those classes are virtual parts themselves.