Created
April 21, 2012 00:13
-
-
Save hpcx82/2432770 to your computer and use it in GitHub Desktop.
sealed(final) class in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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