cplusplus.co.il

Final/frozen classes in c++

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

About these ads

4 Responses to "Final/frozen classes in c++"

I think you meant “sealed” for C#.

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.

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

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 27 other followers

%d bloggers like this: