Re: some casting questions
On Jun 17, 4:10 pm, Jess <w...@hotmail.com> wrote:
On Jun 17, 10:55 pm, James Kanze <james.ka...@gmail.com> wrote:
On Jun 17, 5:48 am, Jess <w...@hotmail.com> wrote:
[...]
class VB {} ;
class L : public virtual VB {} ;
class R : public virtual VB {} ;
class MD : public L, public R {} ;
In other words, because both L and R inherit virtually from VB,
they both share the same instance.
Thanks again! I haven't used virtual inheritance... What is it to
"share" the same instance? Does it mean that if I create an object of
class L, then the object is shared by R? Not quite sure what it
means...
If you have the above declarations, it means that if you create
an L, it has its own VB, if you create an R, it has its own VB,
but if you create a MD, there is only one instance of VB in the
hierarchy; the R and the L in the MD share the single VB. (It's
sometimes confusing because you have to declare the inheritance
virtual in L and in R, but the virtuality really only comes into
play when you derive from L and R. But the compiler needs to
know whether VB might be shared or not when it generates the
code for L and R, so there's no way around it.)
If you recall, my original posting had an inheritance graph:
VB
/ \
L R
\ /
MD
Notice that there is only one VB, and that is it the base class
of both L and R. Without the "virtual" in the inheritance, the
graph would be:
VB VB
\ /
L R
\ /
MD
, with two instances of VB. As an interesting sidelight:
In the first case, with virtual inheritance, you can use a
static_cast to go from MD* to VB*, but not the reverse (because
there is a special restriction on static_cast). In the second,
you can use a static_cast to go from VB* to MD*, but not the
reverse (because the cast would be ambiguous: which VB?). You
can use a dynamic_cast to move anywhere in the hierarchy in the
first case, but MD* to VB* is still ambiguous in the second.
Most of the time, when you inherit from an interface, etc., the
inheritance should probably be virtual. You don't often really
need it, but you don't really know that you won't need it until
you hit classes lower down in the hierarchy. And it might be
another user who runs into the problem, and doesn't have the
right to modify your classes. Many people don't, however,
because it is needed so rarely.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34