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 Class2class Monster {3 public:4 string Shout() {5 return "WSDFSFDS";6 }78 private:9 int hearts;10}111213// Derived Class14class Wumpus : public Monster {15 public:16 string Shout() {17 return "wummmmmwummmmmwummmmmwummmmm";18 }1920 private:21 bool isVisible;22}2324int main() {25 Wumpus derived;2627 cout << derived.Shout() << endl;2829 return 0;30}31
Calling main()
would produce the following output:
1$ ./monster2wummmmmwummmmmwummmmmwummmmm3$ echo $?405
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 Class2class Monster {3 public:4 string Shout() {5 return "WSDFSFDS";6 }78 private:9 int hearts;10}111213// Derived Class14class Wumpus : public Monster {15 public:16 string Shout() {17 return Monster::Shout() + "wummmmmwummmmmwummmmmwummmmm";18 }1920 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$ ./monster2WSDFSFDSwummmmmwummmmmwummmmmwummmmm3$ echo $?405
C++ Inheritance Articles
- C++ Inheritance: Subclass Definition (Pt. 1)
- C++ Inheritance: Protected Member Access (Pt. 2)
- C++ Inheritance: Inheritance Access Levels (Pt. 3)
- C++ Inheritance: Polymorphism (Pt. 5)
Written by Riley Miller, follow me on Twitter 🐦