views:

132

answers:

2

Hi, 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 ?

A: 

Not via an explicit keyword. Some languages have a "sealed" keyword, or similar, that does exactly that, but not C++.

It can be done, (see that useful comment from liaK) but it's really awkward, you would have to have a really good reason to want to do it.

Spike
@Spike: seealed keyword is present in non-standard c++(MSVC++). But it can only stop overriding of virtual functions.
bjskishore123
@bjskishore123: Heh. I've been using MSVC++ for years, but I've tried and avoid using *any* of its non standard features. At least on purpose. I've been bitten by noncompliance before, but that's another story. I've never found a really good reason to stop inheritance anyway.
Spike
A: 

There is no equivalent to the final keyword in Java or C♯'s sealed in 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

birryree
Constructors can not be virtual. If you meant destructors - then they either forgot or they really intended on making the destructor non-virtual to indicate you shouldn't be subclassing from them, or to make it really hard for you. At my job we do use the non-virtual destructor to signal the intent, and it is also a practice mentioned in *Effective C++*. If your clients are well behaved (I know, I know) then documenting your restrictions will be sufficient.
birryree
C++ programmers forget to make constructors virtual all the time. I wouldn't use it as a method of signaling. Edit: And by constructors I meant destructors, sorry.
Spike