construction order w/ virtual base classes

C

coltrane

through trial and error I found out that the order of constructing base
classes is altered if one of the base classes is a virtual base class.

with
class A : public B, public C{
};
the construction order is
B C A

where
class A : public B, public virtual C{
};
the construction order is
C B A

what is the reason for this?

thanks for the help

john
 
J

James Kanze

through trial and error I found out that the order of
constructing base classes is altered if one of the base
classes is a virtual base class.
with
class A : public B, public C{};
the construction order is
B C A
where
class A : public B, public virtual C{};
the construction order is
C B A
what is the reason for this?

What do you want it to be? The same virtual base can be
inherited several times in your hierarchy, so it can't be
initialized by the class immediately above it (unless you want
its constructor called twice). So the constructor has to be
called from somewhere higher in the hierarchy. The simplest
solution is the one adopted: call it from the most derived
class. In a very real sense, a virtual base belongs to the
entire hierarchy, and not just the classes which declare it as
base.
 
C

coltrane

In a very real sense, a virtual base belongs to the
entire hierarchy, and not just the classes which declare it as
base.
I guess this says it all. So a virtual base class, no matter where in
the hierarchy it is, is constructed first.

much thanks.
 
C

coltrane

In a very real sense, a virtual base belongs to the
entire hierarchy, and not just the classes which declare it as
base.
do you know what section I might find this described?
thanks again
 
J

James Kanze

On 8/24/2010 12:33 PM, James Kanze wrote:>
I guess this says it all. So a virtual base class, no matter
where in the hierarchy it is, is constructed first.

First, and by the most derived class. Beware of things like:

class VB
{
protected:
VB(int); // So no default ctor...
};

class L : public virtual VB
{
public:
L() : VB(1) {}
};

class R : public virtual VB
{
public:
R() : VB(2) {}
};

class D : public L, public R
{
public:
D() {}
};

This won't compile, because VB's constructor will be called by
D: since D doesn't specify anything, it will try to use the
default constructor, which doesn't exist. (And in this
hierarchy, the initialization of VB in L and R is never actually
used.)

As a general rule, this isn't a problem; virtual bases normally
define interfaces, and as such, have no data (and thus a default
constructor).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top