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:
Answers to questions are automatically generated and may not have been reviewed.
A crash tour on how we can create custom types in C++ using classes, structs and enums