'Prevent combinational explosion in classes
I have a project in which I have implemented a state machine framework in C++ based upon Miro Samek's statecharts framework (https://www.state-machine.com/). In the basic design, there is a class called StateMachine from which all classes wishing to make use of state machine behavior inherit from. The StateMachine base class contains all of the "boiler plate" code to make a state machine work.
The state machine framework presented in Samek's book also supports additional features like: transitioning to history, deferred events, etc... However, most of the state machines I would write do not need these features.
My first (bad) thought was to do something like:
class StateMachine;
class StateMachineWithHistory : public StateMachine;
class StateMachineWithDeferredEvents : public StateMachine;
There is an immediate problem with this if I want a state machine implementation to have both features. I believe this type of problem is call "combinational explosion."
My second idea was to use virtual inheritance instead:
class StateMachine;
class StateMachineWithHistory : public virtual StateMachine;
class StateMachineWithDeferredEvents : public virtual StateMachine;
class MyStateMachine : public StateMachineWithHistory , public StateMachineWithDeferredEvents;
I ran a test and this seems to be a valid solution. However, it makes me ask the question, what is the overhead of using virtual inheritance? I assume it is the same as introducing virtual methods?
Is there an alternative (better) option I should consider?
EDIT
I want to clarify that the reason I thought of virtual inheritance was because, in my mind, what I am trying to express in words is the following:
MyStateMachine is a StateMachine and also has the features of history and deferred events. A state machine with deferred events is a state machine. A state machine with history is a state machine.
The "is a" wording usually implies inheritance. I suppose the other (less obvious to me) way to express this would be:
MyStateMachine makes use of the features offered by a state machine, a deferred events, and history. The deferred event and history features require the features offered by a state machine.
or
MyStateMachine behaves like a state machine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
