I understand that virtual inheritance of a base class creates a common shared base class among multiple derived classes, thus addressing the DDD problem. If I have only one derived class for my base class, is there a difference when I inherit the base virtually or non-virtually ? Basically I am trying to understand explanation provided in the query Is it possible to forbid deriving from a class at compile time? where Usage_lock base class is inherited virtually to prevent derivations from the class Usable. If I remove this virtual key, the behaviour changes i.e. I am able to derive subclasses from Usable. So I want to understand difference cause by virtual key in single inheritance scenarios.
The primary difference in a single virtual inheritance case is that only the most-derived class calls the constructor of virtually inherited bases, and all of the other classes are provided a reference to the constructed class (this happens behind the scenes).
So, in the example, the since attempting to further derive Usable
would require the new class to call the Usable_lock
constructor (which is private), it is impossible for any other classes to be derived from Usable
. Only Usable
is allowed to construct the lock object, due to it being a friend of the lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With