When to Use Public Inheritance
In what situations is it appropriate to use public inheritance in C++?
Public inheritance is appropriate when there is an "is-a" relationship between the derived class and the base class.
For example, consider a game with a Character base class and derived classes representing player characters and non-player characters (NPCs).
We can say a Player "is a" Character, and an NPC "is a" Character. They share common attributes and behaviors that can be inherited from Character.
class Character {
public:
void Move() {/*...*/ }
protected:
int health_;
};
class Player : public Character {
public:
void SpecialAbility() {/*...*/ }
};
class NPC : public Character {
public:
void Dialogue() {/*...*/ }
};Here, Player and NPC inherit the Move() function and health_ member from Character, but also add their own unique functionality.
Public inheritance allows us to treat derived objects as if they were base objects. For example, we could have a std::vector<Character*> that stores pointers to both Player and NPC objects.
Use public inheritance when:
- The derived class "is a" specialization of the base
- You want the base class interface to be available to users of the derived class
- You want to be able to use derived objects in place of base objects
Classes, Structs and Enums
A crash tour on how we can create custom types in C++ using classes, structs and enums