From link http://www.coolinterview.com/interview/10842/
Is there any way to write a class such that no class can be inherited from it ?
From suggestions in the above link, i tried below code
class A
{
A(){}
~A(){}
A(const A&);
A& operator=(const A&);
};
class B: public A
{
};
The above code doesn’t produce any error.
If i try to instantiate B like below
int main()
{
B ob;
}
then it gives error
error C2248: ‘A::A’ : cannot access
private member declared in class ‘A’
So inheritance its allowing but instantiation its not allowing.
Is there any other way of blocking inheritance itself ?
There is no equivalent to the
finalkeyword in Java or C♯’ssealedin C++. You can certainly prevent inheritance by making the class constructors private, or by following liaK’s link and having a class subclass a class that has private constructors and is its friend.In general though:
You can just make your destructor non-virtual to signal that you do not intend for the class to be polymorphic, and document that this is your intention. Of course, if users of your class decide to ignore this, they could run into problems of their own for their hubris. 😉
Additionally: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.11