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 there is some annoying code duplication in our two introduce() functions. To add on to what the Person class does, the Student class repeats the code from Person and then adds some more code. How can we avoid that?(Remember: Copy and paste is a design failure!
What we can do is to have the Student version of introduce call the Person version. To do that, we call Person::introduce() from within the Student version:
void introduce() const {
    Person::introduce();
    cout << "My major is " << m_major << "." << endl;
}
The order 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();
}
If the function returns some data, we could store that and make use of it. Say the introduce function returned a string. We might write the Student version like:
string introduce() const {
    string intro = Person::introduce();
    return "My major is " + m_major + ".\n" + intro;
}

Note 19.5.1.

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.