Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created April 21, 2012 00:13
Show Gist options
  • Save hpcx82/2432770 to your computer and use it in GitHub Desktop.
Save hpcx82/2432770 to your computer and use it in GitHub Desktop.
sealed(final) class in C++
#include <iostream>
using namespace std;
// Use 2 language features:
// 1. Derived classes through private inheritance can access base class's protected member, but make it private to its sub classes
// 2. Virtual inheritance will cause the final derived class to call the virtual bases's constructor directly
// so the sealed class has no problem to create instance while its sub class can't create instance.
// This is also another use of CRTP (curious recurring template pattern)
template <class T>
class SealedBase
{
protected:
SealedBase(){}
};
#define Sealed(class_name) private virtual SealedBase<class_name>
class Dog : Sealed(Dog)
{
};
class BigDog: public Dog
{
};
int main(int argc, const char* argv[])
{
Dog d;
//BigDog bd;
//BigDog* pBg = new BigDog();
cout << "Hello, World" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment