Can somebody explain why it is so ?
views:
38answers:
2The virtual base is initialized first because any subset of base classes might inherit from it.
The alternative is to attempt to have them coordinate so the first one to inherit initializes the virtual base. That would be clumsy and unpredictable.
Imagine the classic, diamond-shaped multi-inheritance scenario with a virtual base class VB. The inheritance graph for this looks like this
VB VB
| |
| |
D1 D2
\ /
\ /
DD
while the object graph (showing base class sub-objects and their relations) looks like this:
VB
/ \
/ \
D1 D2
\ /
\ /
DD
Generally speaking (and leaving virtual bases out of the picture), classes are constructed base-to-derived, so any base class sub-objects must be created before the derived classes are created. For our concrete example this means:
When a DD object is created, two sub-objects, of the types D1 and D2, need to be created first. However, in order to create these, their base class sub-objects need to be created first...which is problematic, because they share the same sub-object.
The solution to this is to first create the virtual base class sub-object, and then the rest of them.