Final (frozen) classes in c++

September 1st, 2009 § 4 Comments

A final (or frozen) class is a class that can’t be further extended by inheritance. Different languages define different keywords for such behavior – for example “final” in Java, or “sealed” in c#. Unfortunately we don’t have such construct in c++; but we can use other mechanisms to easily achieve this goal.

As I have previously 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.

§ 4 Responses to Final (frozen) classes in c++

  • George Faraj says:

    I think you meant “sealed” for C#.

    • rmn says:

      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.

  • Ofek says:

    Wouldn’t it suffice to make Frozen’s constructor private?

    • rmn says:

      If Frozen’s constructor is private, the class is severely limited: no one can create instances of the class. We were looking for a solution that will not impose any restrictions on the Frozen class.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What’s this?

You are currently reading Final (frozen) classes in c++ at 0x.

meta