RAD Studio
ContentsIndex
PreviousUpNext
Virtual Base Classes

A virtual class is a base class that is passed to more than one derived class, as might happen with multiple inheritance. 

You cannot specify a base class more than once in a derived class:

class B { ... };
class D : B; B { ... }; //ILLEGAL

However, you can indirectly pass a base class to the derived class more than once:

class X : public B { ... };
class Y : public B { ... };
class Z : public X, public Y { ... }; //OK

In this case, each object of class Z has two sub-objects of class B. 

If this causes problems, add the keyword virtual to the base class specifier. For example,

class X : virtual public B { ... };
class Y : virtual public B { ... };
class Z : public X, public Y { ... };

B is now a virtual base class, and class Z has only one sub-object of class B. 

Constructors for Virtual Base Classes 

Constructors for virtual base classes are invoked before any non-virtual base classes. 

If the hierarchy contains multiple virtual base classes, the virtual base class constructors invoke in the order they were declared. 

Any non-virtual bases are then constructed before the derived class constructor is called. 

If a virtual class is derived from a non-virtual base, that non-virtual base will be first, so that the virtual base class can be properly constructed. For example, this code

class X : public Y , virtual public Z
 X one;

produces this order:

Z(); // virtual base class initialization
Y(); // non-virtual base class
X(); // derived class
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!