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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Classes vs Structs in C++
What are the key differences between classes and structs in C++, and when should I use one over the other?
Multiple Constructors with the Same Name
How can a class have multiple constructors with the same name?
When to Use Member Initializer Lists
What are the benefits of using member initializer lists in constructors?
Implicitly-Defined Default Constructors
When does the compiler implicitly define a default constructor for a class?
Using Destructors for Resource Management
How can I use destructors to manage resources in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant