Practical use of 'protected' specifier in C++

c++, protected

Solution

A class has two APIs - one for code that instantiates it and uses the resulting objects, and one for subclasses.

The first API is the `public` members, while the second is the `public` and `protected` members. There are operations and data that it's OK for a subclass to access that it isn't OK for "ordinary users" to access.

As a concrete example, imagine a Windows GUI class library. It wraps and hides the plain old Windows API. A `Window` represents a window, and has an `HWND` which is the underlying Windows window handle. It hides the `HWND` from users of the `Window` class, because it's none of their business (or if it's OK for them to use it, it only exposes it via a read-only accessor). But it's OK for subclasses of `Window`, like `FrameWindow` or `EditControl`, to access the `HWND` directly:

class Window
{
public:
    void Show();  // Example public API

protected:
    HWND m_hwnd;
};

Problem

I know how this specifier works. I'm interested in practical usage of this stuff in real programming. I can't imagine any example where protected class members are really necessary (I mean when we can not to replace 'protected' with 'private').

Original source