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.
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 {
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;
}
Note19.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.
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.