共用方式為


Initializing Base Classes

Direct base classes are initialized in much the same way as member objects. Consider the following example:

// spec1_initializing_base_classes.cpp
// Declare class Window.
class MyClass
{
public:
   MyClass( int rSize )
   {
   }
};

//  Declare class DialogBox, derived from class MyClass
class DialogBox : public MyClass
{
public:
   DialogBox( int rSize );
};

//  Define the constructor for DialogBox. This constructor
//   explicitly initializes the MyClass subobject.
DialogBox::DialogBox( int rSize ) : MyClass( rSize )
{
}

int main()
{
}

Note that in the constructor for DialogBox, the Window base class is initialized using the argument rSize. This initialization consists of the name of the base class to initialize, followed by a parenthesized list of arguments to the class's constructor.

In initialization of base classes, the object that is not the subobject representing a base class's component is considered a "complete object." The complete object's class is considered the "most derived" class for the object.

The subobjects representing virtual base classes are initialized by the constructor for the most derived class. That means that where virtual derivation is specified, the most derived class must explicitly initialize the virtual base class, or the virtual base class must have a default constructor. Initializations for virtual base classes that appear in constructors for classes other than the most derived class are ignored.

Although initialization of base classes is usually restricted to direct base classes, a class constructor can initialize an indirect virtual base class.

See Also

Concepts

Initializing Bases and Members