Tuesday, February 07, 2006

Final classes

i camed across a nice C++ question which shows the final class principle (as I read here: http://www.codeguru.com/Cpp/Cpp/cpp_mfc/stl/article.php/c4143/ it seems that the final class specifier exist in Java)

1. A class that is not derived from a class nor is intended to have any class derived from it is an example of what type of class?
A. A concrete class
B. An abstract class
C. A base class
D. A virtual class
E. A final class

A final class is a class from which you dont derive (if you try to, the objects of the derived classes cant be constructed since the compiler will complain about this).
So how can you design such class ?

In C++ there is no keyword (final) to declare a class as non-inheritable as in Java.
But then C++ has its own features which you may exploit to get the same behaviour.
Basically it uses concepts of private constructor and friend class.

For example, lets try to create a class called CFinal.
class CFinal
// member data ...

We want to be able to use this class, of course, to create objects from it but what we dont want is to be able to use this class as a base for other classes. Or, in other words, if anybody creates a class derived from CFinal, it will not be able to create objects of this derived class.

The first idea will be to make the CFinal constructors private but doing so will prevent us to create objects of it. We need to way to be able to make construction unavailable for the derived classes only.

The solution:
We use the fact that in C++, if a class has a friend class, the friendship is not inheritate in any way; if the friend class has a derived class, this does not mean that the derived class is a friend also for the initial class

class Temp
private: ~Temp() { };
friend class CFinal;

class CFinal : virtual public Temp
{. . .};

Again, if we have this:
class CDerived : CFinal
{. . .}
CDerived is NOT a friend of the Temp class.

So that now if some one tries to inherit from this CFinal class, compilation gives error as this class cannot call constructor of its super class i.e.
Yet, you can create CFinal objects, because as a friend of the Temp class, your class has access to the private constructor.

The whole idea i got it from this article:
"Working with the Final Class in C++" by Zeeshan Amjad

No comments: