6

Here http://www.parashift.com/c++-faq-lite/multiple-inheritance.html section [25.14] says

The very first constructors to be executed are the virtual base classes anywhere in the hierarchy.

I tried to verify it using following program:

           A (pure virtual)
           |
           B
           |
           C
(virtual)/   \ (virtual)
       E       D
         \   /
           F
           |
           G (pure virtual)
           |
           H

each class has a c'tor and virtual d'tor. the output is as follows:

A
B
C
E
D
F
G
H
~H
~G
~F
~D
~E
~C
~B
~A
Press any key to continue . . .

but as per quote virtual base classes constructors should be executed first.

what did I understand wrong?

EDIT: To clear my question, As per my understanding this behaviour has nothing to do with whether a base class is virtual or not. but quote insists on Virtual Base class. am I clear or something fishy there?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Azodious
  • 13,752
  • 1
  • 36
  • 71

1 Answers1

6

Virtual base classes cannot be constructed if the classes they inherit from are not constructed first. So in your case, non-virtual base classes are constructed because the virtual ones depend on them: C can't be constructed until A and Bare. Therefore, A and B are indeed constructed before C, even though C is virtually inherited.

Eran
  • 21,632
  • 6
  • 56
  • 89
  • 1
    That's in any scenerio. why this phrase is added `anywhere in the hierarchy`? – Azodious Aug 16 '11 at 14:07
  • 2
    @Azodious, C++ FAQ is fantastic, but I guess in this case the lack of further explaining might actually be somewhat misleading. Virtual base classes are constructed first anywhere, but constructing them involves constructing their bases, as in any scenario. No other way for it to work, as classes have to be able to rely on their bases being initialized. – Eran Aug 16 '11 at 14:40
  • It's possibly a bit _too_ strict, or alterntaively you're reading it too literally. With virtual inheritance, a class can appear in multiple times anywhere in the hierarchy. That means it can have quite a lot of siblings. We don't want to specify precisely when a virtual base class is constructed relative to its siblings, so we've adopted the "before any _possible_ sibling in the hierachy" rule, but that still doesn't invalidate the "after your own base classes" rule. After all, you can't be a sibling of your own base class, unless that too is a virtual base class. – MSalters Aug 16 '11 at 14:44