RAD Studio |  |

Virtual Base Classes
See Also
Collapse All

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:

Copy Code

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

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

Copy Code

    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,

Copy Code

    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

Copy Code

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

produces this order:

Copy Code

    Z(); // virtual base class initialization
    Y(); // non-virtual base class
    X(); // derived class

See Also

C++ Classes

Class Types

Class Scope

Class Objects

Class Member List

Member Functions

The Keyword This

Static Members

Inline Functions

Member Scope

Nested Types

Member Access Control

Base And Derived Class Access

Virtual Base Classes

Friends Of Classes

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!