The Life of a Programmer

Curiously protective C++

Working with a bit of code last week I stumbled into something unusual. I was working on something quite basic so kind of surprised when I came across a compilation error. GCC was telling me that I couldn’t access a protected member. Thinking I understood the concept of inheritance I was quite confused as to why I got this error message. Can you spot the problem in the code below?

class base
    int a;

class derived : protected base
    int sum;
    void add( base const & o )
        sum += o.a;        //error here, why?

My difficulty perhaps had a lot to do with working in various languages; this is my first major C++ project in a few years. While the concepts of OOP migrate between the languages well, there are some tricky bits. The code above is a very good example of how the fine points of languages tend to differ. For example, if you converted the above into the most equivalent Java code you’d find that you don’t get an error, it works exactly as you intended.

Just to review, how should protected inheritance work? In this case the protected inheritance doesn’t actually matter, it could be replaced with public inheritance (as it would in the Java equivalent). The variable a is protected in the base class. That means that derived classes are allowed to access it. That is essentially what protected means, as opposed to private in which the derived class could not access it. So why then can’t the add function access a?

If the add function had the signature void add( derived const & o) it would work. This is the strongest clue as to what is wrong. In it’s current form the parameter is of type base and not of type derived. The access to protected members is only for the derived class, in this case the parameter is not the derived class, thus access is restricted. I haven’t checked the standard, but I’d suspect it actually says as much. Does it make sense?

Rephrase that, is there a manner in which that without this restriction you’d be able to do something wrong? That is often a good test. In this case however I can’t think of such a situation. That is, it seems to me that Java is correct here and you should be able to access that protected member. I’d like to know if anybody else could come up with a situation to demonstrate a problem. I’m also curious as to what other languages do in this regards.

Please join me on Discord to discuss, or ping me on Mastadon.

Curiously protective C++

A Harmony of People. Code That Runs the World. And the Individual Behind the Keyboard.

Mailing List

Signup to my mailing list to get notified of each article I publish.

Recent Posts