Re: construction order w/ virtual base classes
On Aug 24, 5:40 pm, coltrane <tendenga...@yahoo.com> wrote:
On 8/24/2010 12:33 PM, James Kanze wrote:>
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.
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).
--
James Kanze