Classes, Structs and Enums

When to Use Public Inheritance

In what situations is it appropriate to use public inheritance in C++?

Abstract art representing computer programming

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

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved