Final (frozen) classes in c++

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 .

5 thoughts on “Final (frozen) classes in c++

    1. 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.

    1. 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.

  1. This solution is not perfect unfortunately. If I’m a developer that wants to inherit from your class and create final/sealed class than this is still possible:

    class X : public Frozen, public virtual Freeze {};

    and now X is “final” inheriting from “final” :)

Leave a Reply

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