Posted by: rmn on: 01/09/2009
A final (or frozen) class is a class that can’t be further extended by inheritance. In many languages we have different keywords for such behaviour, such as “final” in Java, or “sealed” in c#. Unfortunetly we don’t have such construct in c++; but we can use other mechanisms to easily achieve this goal.
As i’ve mentioned in the article about constructor selection (and invocation) with virtual inheritance (link), we can exploit the same mechanism here:
class Frozen;
class Freeze {
Freeze () {}
friend class Frozen;
};
class Frozen : public virtual Freeze {
};
Since the constructor of Freeze is private, only Frozen can call it – because Frozen is declared as a friend to Freeze. Due to the usage of virtual inheritance, the most deriving class is the one that must call Freeze’s constructor. Therefore, no other class can be derived from Frozen (without altering Freeze’s definition), and we have achieved our goal.
This solution can also be found in Bjarne Stroustrup’s FAQs.
Wouldn’t it suffice to make Frozen’s constructor private?
02/09/2009 at 01:00
I think you meant “sealed” for C#.
02/09/2009 at 20:46
I did, thanks!
I used the term “frozen” since sometimes final classes are referred to as being “frozen”, and the keyword “sealed” is used in c# to denote such situation.