Re: Constructors and virtual inheritance...
DeCaf wrote:
If we have a situation where a base class A has only a non-default
constructor, two classes B and C derived by virtual inheritance has
abstract methods, and a class D inheriting from both B and C. It
seems that the constructor of B and C must be defined and call
A::A(args), even though neither B nor C will ever be the class to
actually make the call to A::A, since that will always be done by the
most derived class (in this case D). Is this really so?
In practice, at any case. I seem to recall that the standard
was a bit vague about this, but I rather suspect that it
corresponds to the intent.
If so, it
seems like a bit of an annoyance, because either I'd have to put in a
bogus value in the initializer lists of B and C's call to A::A (which
makes the code less obvious), or I would have to create non-defautl
constructors for both B and C that would pass on its arguments to A::A,
however this would mean D had to make three explicit constructor calls
from its constructor with the same parameter, but with only one call
actually making the difference.
Since both B and C are abstract in the case above, I don't see why I
have to define constructors that initialize A, but both GCC and MSVC++
7.1 seems to think that this is what I should do.
What is the recommended way of handling this?
I don't know if it's exactly recommended, but what I do is
provide a protected default constructor to the virtual base,
which just aborts with an error message:-).
Note that this is only an acceptable solution in a closed
hierarchy (where you control all of the derived classes). In an
open hierarchy, you must provide a real default constructor to
the virtual base, even if it means dummy initialization, with
the real initialization being performed in a function called by
one of your derived classes. Such cases are rare, however: the
most frequent use of virtual inheritance is of interfaces (in
which case, the only constructor of the base takes no
parameters, since the class has no data to initialize), and the
second, but very far behind, is probably mixin's in a closed
hierarchy. (But of course, I'm only judging from my own code
concerning these frequencies, so you may want to take them with
a grain of salt.)
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]