C++ Protected Class Members

Learn about protected members within classes, and how they differ from public and private members.
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

3D art showing a dragon character
Ryan McCombe
Ryan McCombe
Posted

We have previously seen how we can (and should) make some of the variables and functions of our class private, to prevent code from outside of our class accessing them.

class Character {
private:
  int Health { 100 };
};

The following code will not compile, as private members cannot be accessed from outside the Character class:

class Monster : public Character {
public:
  int GetHealth() { return Health; }
};

We could make Health public again, but we've already seen why that can be problematic. But equally, child classes are inherently linked to their parent. Locking them out from accessing large parts of the parent class can be quite restrictive.

Fortunately, we do have an access level between public and private that solves this problem. This access level is called protected.

protected members cannot be accessed by functions that exist outside our class hierarchy, but they can still be accessed by child classes. This is exactly what we need to solve our problem:

class Character {
protected:
  int Health { 100 };
};

class Monster : public Character {
public:
  void GetHealth() { return Health; }
};

To summarise:

  • private members are only accessible within that same class
  • protected members are accessible within that same class, and any sub class
  • public members are accessible to any code

Test your Knowledge

What are the three access specifiers we have for classes?

What is the difference between protected and private access?

Was this lesson useful?

Ryan McCombe
Ryan McCombe
Posted
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Inheritance
3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access!

This course includes:

  • 66 Lessons
  • Over 200 Quiz Questions
  • Capstone Project
  • Regularly Updated
  • Help and FAQ
Next Lesson

Static Overloading in C++

See how we can create different versions of functions by using different parameter types
3D art showing a character using a compass
Contact|Privacy Policy|Terms of Use
Copyright © 2023 - All Rights Reserved