Riley Miller

C++ Inheritance: Overriding Base Class Methods (Pt. 4)

July 06, 2020

Oftentimes when defining a derived class, you need to add specific functionality to a method inherited from the base class to suit the needs of the subclass. This process is called overriding.

There is an important distinction between overriding and overloading. Overriding refers to the process of redefining a method inherited from the base class that contains the same parameters. Whereas, overloading refers to the process of defining a method in the derived class with the same name but different parameters.

An example of method overriding is:

1// The Base Class
2class Monster {
3 public:
4 string Shout() {
5 return "WSDFSFDS";
6 }
7
8 private:
9 int hearts;
10}
11
12
13// Derived Class
14class Wumpus : public Monster {
15 public:
16 string Shout() {
17 return "wummmmmwummmmmwummmmmwummmmm";
18 }
19
20 private:
21 bool isVisible;
22}
23
24int main() {
25 Wumpus derived;
26
27 cout << derived.Shout() << endl;
28
29 return 0;
30}
31

Calling main() would produce the following output:

1$ ./monster
2wummmmmwummmmmwummmmmwummmmm
3$ echo $?
40
5

Calling Base Class Functions

Sometimes when overriding functions you wish to add functionality at the derived class level instead of completely overhauling the inherited function. To call a base class function within a derived class, you would write the base class name followed by the scope resolution operator (::):

1// The Base Class
2class Monster {
3 public:
4 string Shout() {
5 return "WSDFSFDS";
6 }
7
8 private:
9 int hearts;
10}
11
12
13// Derived Class
14class Wumpus : public Monster {
15 public:
16 string Shout() {
17 return Monster::Shout() + "wummmmmwummmmmwummmmmwummmmm";
18 }
19
20 private:
21 bool isVisible;
22}
23

When calling the base class method within the derived class method override, the derived class Shout() method would now output:

1$ ./monster
2WSDFSFDSwummmmmwummmmmwummmmmwummmmm
3$ echo $?
40
5

C++ Inheritance Articles


Written by Riley Miller, follow me on Twitter 🐦

//