Overriding the Definitions of Member Functions

Let’s discuss how to override the definitions of member functions.

We'll cover the following


One of the benefits of inheritance is being able to redefine the member functions of the superclass in the subclass. This is called overriding: The existing definition of the member function of the superclass is overridden by the subclass with the override keyword.

Overridable functions are called virtual functions. Virtual functions are implemented by the compiler through virtual function pointer tables (vtbl) and vtbl pointers. The details of this mechanism are outside the scope of this course. However, it must be known by every system programmer that virtual function calls are more expensive than regular function calls. Every non-private class member function in D is virtual by default. For that reason, when a superclass function does not need to be overridden at all, it should be defined as final so that it is not virtual. We will see the final keyword later in the interfaces chapter.

Let’s assume that Clock has a member function that is used for resetting all its members to zero:

class Clock {
    void reset() {
        hour = 0; 
        minute = 0; 
        second = 0;
    // ...

That function is inherited by AlarmClock and can be called on an AlarmClock object:

Get hands-on with 1000+ tech skills courses.