Click here to Skip to main content
13,298,088 members (52,982 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


17 bookmarked
Posted 2 Sep 2009

Sealing Classes in C++

Rate this:
Please Sign up or sign in to vote.
A method to create sealed classes in C++


Some recent languages like C# and Java allow you to seal your classes easily using a keyword like sealed or final respectively. C++ doesn't have any such keyword for this purpose. However, it's possible to still do it using a trick. When using virtual inheritance, the initialization list of the most-derived-class's constructor directly invokes the virtual base class's constructor. This means that if we can hide access to the virtual base class's constructor, then we can prevent any class from deriving from it. This mimics the effect of being sealed.

Solution Attempt #1

To provide an easy way to seal classes, we can write a header file Sealed.h like this:

class SealedBase

#define Sealed private virtual SealedBase 

Now to seal a class, say Penguin, we just need to derive it from Sealed, like this:

#include "Sealed.h"

class Penguin : Sealed

That's it. Penguin is now a sealed class. Let's try deriving another class, BigZ (Surf's Up (2007), anyone?) from Penguin

class BigZ : Penguin

BigZ bigZ; // error C2248 

Instantiating an object of BigZ should yield a compiler error. The MSVC++ 2005 compiler gives me the following error message:

error C2248: 'SealedBase::SealedBase' : cannot access inaccessible member 
declared in class 'SealedBase'

A Serious Flaw

All seems to be working well. However, one of my fellow programmers, Angelo Rohit, pointed out to me that this method has a serious flaw in it. Angelo says that if BigZ derives from Penguin and Sealed, then it will be possible to create objects of BigZ:

class BigZ : Penguin, Sealed

BigZ bigZ; // OK; no compiler error 

Why does this happen? BigZ derives from Sealed just like Penguin does, which means that it now has access to Sealed's constructor. And since Sealed is inherited virtually by both Penguin and BigZ, there is only one copy of it - which is now also accessible to BigZ. Bummer. We need to have a mechanism by which BigZ is forced to call the constructor of a class which it doesn't have access to.

Solution Attempt #2

After pondering over this for a while, I realized that if we can somehow generate different base classes every time Sealed is derived from, then it would work.

Let's rewrite the Sealed.h header to look like this:

template <int T>
class SealedBase

#define Sealed private virtual SealedBase<__COUNTER__>

What does this do? SealedBase is now a templated class which takes an integer as an argument. __COUNTER__ is a predefined macro which expands to an integer starting with 0 and incrementing by 1 every time it is used in a compiland. So every time Sealed is derived from, it generates a new SealedBase class using the incremental number which __COUNTER__ expands to.

Now let's go back to our BigZ class which derives from both Penguin and Sealed:

class BigZ : Penguin, Sealed

BigZ bigZ; // error C2248

This time around though, BigZ can't escape from the compiler. Penguin derives from SealedBase<number1> and BigZ derives from SealedBase<number2>, where number1 and number2 are two non-identical integers. So now BigZ has to invoke the constructor of SealedBase<number1>, which it doesn't have access to.

The MSVC++ 2005 compiler gives me the following error message:

error C2248: 'SealedBase<T>::SealedBase' : cannot access inaccessible member 
declared in class 'SealedBase<T>'
1> with
1> [
1> T=0
1> ]

Portability Issues

However, you might be thinking that since we're using a special predefined macro __COUNTER__ in our implementation, this code is not portable. Well, it's supported by MSVC++ (which I used to test the above code) and also by GCC (

But what about compilers which don't?

A Portable Solution 

After a little thought, I came up with the following way:

In Sealed.h:

template <class T>
class SealedBase

#define Sealed(_CLASS_NAME_) private virtual SealedBase<_CLASS_NAME_>

And to seal a class:

#include "Sealed.h"

class Penguin : Sealed(Penguin)

When sealing a class, we need to mention that class's name to the Sealed macro. This enables the Sealed macro to generate a new version of SealedBase. This is less elegant than simply having to derive from Sealed, but is more portable, making it a good alternative for compilers which don't support the __COUNTER__ predefined macro.

Final Words

People who use MSVC++ or GCC can simply use Solution Attempt #2, as it is cleaner. People on other compilers, can use the Portable Solution. If you have any questions, suggestions, improvements, or simply want to say hi, please email me.

Thanks for reading!
Francis Xavier


  1. C++ Q&A: List View Mode, SetForegroundWindow, and Class Protection
  2. Vladislav Lazarenko: "[boost] Sealed C++ class"


  • 2nd September, 2009: Initial post


This article, along with any associated source code and files, is licensed under The MIT License


About the Author

Francis Xavier Pulikotil
Software Developer
United States United States
Besides loving spending time with family, Francis Xavier likes to watch sci-fi/fantasy/action/drama movies, listen to music, and play video-games. After being exposed to a few video-games, he developed an interest in computer programming. He currently holds a Bachelor's degree in Computer Applications.

You may also be interested in...

Comments and Discussions

QuestionThanks Francis Pin
consthab210-Apr-13 4:44
memberconsthab210-Apr-13 4:44 
BugPortable solution flaw Pin
Yaroslav Lobachevski6-Dec-12 13:52
memberYaroslav Lobachevski6-Dec-12 13:52 
GeneralThe soluion does not seem simple Pin
Mukit, Ataul20-Feb-11 8:02
memberMukit, Ataul20-Feb-11 8:02 
GeneralSealed class need does exist Pin
Bhushan198023-Feb-10 20:27
memberBhushan198023-Feb-10 20:27 
GeneralSimplier way to make a class sealed Pin
sergey nazarov8-Sep-09 2:37
membersergey nazarov8-Sep-09 2:37 
GeneralRe: Simplier way to make a class sealed Pin
emilio_grv9-Sep-09 23:26
memberemilio_grv9-Sep-09 23:26 
GeneralRe: Simplier way to make a class sealed Pin
Bhushan198023-Feb-10 20:05
memberBhushan198023-Feb-10 20:05 
QuestionWhat is the purpose of a Sealed Class? Pin
hector santos2-Sep-09 19:03
memberhector santos2-Sep-09 19:03 
AnswerRe: What is the purpose of a Sealed Class? Pin
Tim Craig2-Sep-09 19:25
memberTim Craig2-Sep-09 19:25 
GeneralRe: What is the purpose of a Sealed Class? Pin
emilio_grv4-Sep-09 3:42
memberemilio_grv4-Sep-09 3:42 
GeneralRe: What is the purpose of a Sealed Class? Pin
Tim Craig4-Sep-09 8:14
memberTim Craig4-Sep-09 8:14 
GeneralRe: What is the purpose of a Sealed Class? Pin
MJessick5-Sep-09 18:02
memberMJessick5-Sep-09 18:02 
I had an occasion once causing me to wonder how to preclude subclassing without requiring changes to the base class. Thank you for this possible solution to that problem (in general, if perhaps not really useful for the problem I will use as an example). It had to do with not providing a virtual destructor to keep the memory usage of a lightweight class with no other virtual methods as small as possible. Perhaps someone down the road would ignore the code comment not to subclass without changing the base class code to provide a virtual destructor and cause themselves trouble.

How did I learn to consider the memory impacts of virtual functions on small class objects? In a job interview I had parroted what I had been taught about the necessity of always supplying virtual destructors. I even correctly explained the problems my previous company's coding standards (requiring them) were trying to avoid. The interviewer made an offhand comment that it might be better to understand all the issues rather than rely entirely on rigid coding standards in design. Wondering what he had meant in this particular instance, I took the opportunity to learn something by studying the matter further later. (Note for those new to C++: using virtual methods in a class requires a pointer to the class virtual function table be added to each object of a class. This is the start of how the proper virtual functions to call are chosen at run time. So using any virtual functions increases the effective memory size of objects: possibly important if the class is small and its objects are especially numerous.)

SO: This example is about a situation where an optimization has been made that would potentially break code using subclasses. It might be useful to force anyone desiring to derive from this class to analyze whether removing the optimization would be appropriate in order to derive, or perhaps to fully understand the important restrictions not making the change would put on object usage.

- Matt Jessick

GeneralRe: What is the purpose of a Sealed Class? Pin
ryo-oh-ki7-Sep-09 10:49
memberryo-oh-ki7-Sep-09 10:49 
GeneralRe: What is the purpose of a Sealed Class? Pin
emilio_grv8-Sep-09 22:11
memberemilio_grv8-Sep-09 22:11 
GeneralRe: What is the purpose of a Sealed Class? Pin
Tim Craig9-Sep-09 20:22
memberTim Craig9-Sep-09 20:22 
GeneralRe: What is the purpose of a Sealed Class? Pin
emilio_grv9-Sep-09 23:21
memberemilio_grv9-Sep-09 23:21 
GeneralRe: What is the purpose of a Sealed Class? Pin
Filousov7-Oct-15 3:27
memberFilousov7-Oct-15 3:27 
Generalsealed Pin
Goran Mitrovic2-Sep-09 9:08
memberGoran Mitrovic2-Sep-09 9:08 
AnswerRe: sealed Pin
Rich Berlint7-Sep-09 21:06
memberRich Berlint7-Sep-09 21:06 
GeneralRe: sealed Pin
FrancisXavier7-Sep-09 23:16
memberFrancisXavier7-Sep-09 23:16 
GeneralInteresting... Pin
AnandChavali2-Sep-09 4:27
memberAnandChavali2-Sep-09 4:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 2 Sep 2009
Article Copyright 2009 by Francis Xavier Pulikotil
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid