Home > C++ > Access Change

Access Change

To ensure consistency across our application component set in the team project that I’m currently working on, I’m required to inherit from a common base class that resides in a lower, infrastructure layer. However, since my class resides in the topmost, domain-specific layer of our stack, I want to discourage others from inheriting from it – but (as far as I know) there’s no simple way in C++ to do this (no contorted singletons please – it’s overkill).

In addition to inserting a  /*we’ll fire you if you inherit from this class!*/ type comment and removing the virtual keyword from all overridden member functions, I recently discovered an additional, trivial way of discouraging others from inheriting from a class that is intended to be a leaf in an inheritance tree. It may already be an existing C++ idiom that I haven’t stumbled across, but I’ll call it “access change” just in case it isn’t.

The figure below shows what I mean by “access change“. As you can see in the Derived class, in addition to leaving the virtual keyword out of the Derived::mandatory() function definition, I also changed its access qualifier from protected to private.

What do you think? Are there any downsides to this technique? Are there any other “gentle” ways to discourage, but not prevent, other C++ programmers from deriving from a class you wrote that wasn’t intended to be used as a base class?

Categories: C++ Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: