Calling an Inherited Member Function

(ISO C++, §10.3) You can call an inherited virtual member function rather than its local override in two ways. The first method is recommended for referring to member functions defined in a base class or any other parent class. The second method, while more convenient, is not recommended if you are using your source code with other compilers.

The standard method of calling inherited member functions

This method adheres to the ISO C++ Standard and simply qualifies the member function with its base class.

Assume you have two classes, MyBaseClass and MySubClass, each implementing a function named MyFunc().

From within a function of MySubClass, you can call the base class version of MyFunc() this way:

MyBaseClass::MyFunc();

However, if you change the class hierarchy, this call might break. Assume you introduce an intermediate class, and your hierarchy is now MyBaseClass, MyMiddleClass, and MySubClass. Each has a version of MyFunc(). The code above still calls the original version of MyFunc() in the MyBaseClass, bypassing the additional behavior you implemented in MyMiddleClass. This kind of subtlety in the code can lead to unexpected results or bugs that are difficult to locate.

Using inheritance to call inherited member functions

The def_inherited pragma defines an implicit inherited member for a base class. Use this directive before using the inherited symbol:

#pragma def_inherited on

WARNING! The ISO C++ standard does not support the use of inherited.

You can call the inherited version of MyFunc() this way:

inherited::MyFunc();

With the inherited symbol, the compiler identifies the base class at compile time. This line of code calls the immediate base class in both cases: where the base class is MyBaseClass, and where the immediate base class is MyMiddleClass.

If your class hierarchy changes at a later date and your subclass inherits from a different base class, the immediate base class is still called, despite the change in hierarchy.

The syntax is as follows:

inherited::func-name(param-list);

The statement calls the func-name in the class’s immediate base class. If the class has more than one immediate base class (because of multiple inheritance) and the compiler cannot decide which func-name to call, the compiler generates an error.

This example creates a Q class that draws its objects by adding behavior to the O class.

Listing 1. Using inherited to Call an Inherited Member Function

#pragma def_inherited on
struct O { virtual void draw(int,int); };
struct Q : O { void draw(int,int); };

void Q::draw (int x,int y)
{
inherited::draw(x,y); // Perform behavior of base class
... // Perform added behavior
}

For related information on this pragma see “def_inherited”.