Riley Miller

C++ Inheritance: Subclass Definition (Pt. 1)

July 06, 2020

Inheritance is a very useful concept for dealing with object-oriented languages and allows developers to declare generic classes that can then be extended to fit more specific use cases.

In C++, a derived class, is a class that is derived from another class, this class is called the base class. These terms are also sometimes referred to as a subclass for a derived class and a superclass for a base class.

A derived class inherits all of the public properties and members of its base class, this is where the term inheritance stems from. When an object is instantiated for a derived class, the object will have access to all of the public members of both the derived class and the base class.

How to Define a Subclass

Given that any class can be extended to have a derived class, the : operator is used to specify relationships between classes in C++ inheritance. To define a subclass, you would use : and the base class name like:

1// The Base Class
2class Monster {
3 public:
4 void setHealth(int hearts) {
5 this->hearts = hearts;
6 }
7
8 int getHealth() {
9 return this->hearts;
10 }
11
12 private:
13 int hearts;
14}
15
16
17// Derived Class
18class Wumpus : public Monster {
19 public:
20 void Hide() {
21 cout << "Shhhhhhh" << endl;
22 this->isVisible = false;
23 }
24
25 void Appear() {
26 cout << "ARGHHARHGHHHH" << endl;
27 this->isVisible = true;
28 }
29
30 private:
31 bool isVisible;
32}
33

In this case the Wumpus inherits all of the public members of the base class, Monster, and also defines class members that are specific only to the Wumpus class.

C++ Inheritance Articles


Written by Riley Miller, follow me on Twitter 🐦

//