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 Class2class Monster {3 public:4 void setHealth(int hearts) {5 this->hearts = hearts;6 }78 int getHealth() {9 return this->hearts;10 }1112 private:13 int hearts;14}151617// Derived Class18class Wumpus : public Monster {19 public:20 void Hide() {21 cout << "Shhhhhhh" << endl;22 this->isVisible = false;23 }2425 void Appear() {26 cout << "ARGHHARHGHHHH" << endl;27 this->isVisible = true;28 }2930 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
- C++ Inheritance: Protected Member Access (Pt. 2)
- C++ Inheritance: Inheritance Access Levels (Pt. 3)
- C++ Inheritance: Overriding Base Class Methods (Pt. 4)
- C++ Inheritance: Polymorphism (Pt. 5)
Written by Riley Miller, follow me on Twitter 🐦