Skip to main content

Section 19.5 Overriding Members

Sometimes, it is useful for a derived class to modify the behavior of a function that it has inherited. For example, our student class might want to include a message about their major when they introduce() themselves.
To do this, we can override the base class function. To override a function, we simply define a new version of the function in the derived class:
Listing 19.5.1.
Now, when we call introduce() on a student object, that version will be used instead of the inherited one.
In the UML, we would show that introduce() is overridden in the Student class. getName, which is not overridden, is only shown in the base class.
Person and Student classes
          classDiagram
          class Person {
            -m_name: string
            -m_age: int
            +introduce()
            +getName()
          }
          class Student {
            -m_major: string
            +introduce()
          }
          Person <|-- Student
        
      
Figure 19.5.2. UML for Person and Student
You may have noticed that the Student version of introduce prints the same information as the Person version and then adds another line. The output still stars with "Hi, my name is ...". To get this output without duplicating code, the Student version of introduce calls the Person version:
void introduce() const {
    Person::introduce();
    cout << "My major is " << m_major << "." << endl;
}
That syntax allows us to call the parent version of a function from within the derived class version.

Insight 19.5.1.

Donโ€™t Repeat Yourself: Copy and paste is a design failure! Part of the benefit of inheritance is reusing logic in the parent class.
The order of calls is not important - the call to the parent version can happen anywhere. Perhaps we want to print out the Studentโ€™s major first:
void introduce() const {
    cout << "My major is " << m_major << "." << endl;
    Person::introduce();
}
We can use the parent versionโ€™s return value to build the derived versionโ€™s return value. This is seen in the Student version of toString():
string toString() const {
    string personStr = Person::toString();
    return format("{}, Major: {}", personStr, m_major);
}

Note 19.5.2.

You can also use this naming trick to call the inherited version of a function from outside the class. main could call s.Person::introduce() to get the Person version of the function instead of the Student version (assuming s is a Student). However, this is not a trick you should usually need very often.

Checkpoint 19.5.1.

Checkpoint 19.5.2.

Checkpoint 19.5.3.

Manager inherits from Employee which has a double calculatePay() const. Manager wants to override it to calculate the pay including a performance bonus. Build the function as it would look in Manager.
You have attempted of activities on this page.