Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++ Tip #6: Making Classes Non-Derivable


May 2001/C/C++ Tip #6


Sometimes it is useful to create classes that are non-derivable. By explicitly doing so, you reduce the chance of class misuse as well as provide a more clear design intention. A traditional way to make a class non-derivable is to make the constructors of the class private, and provide static member functions such as create, to create the object on the heap and return its address. Unfortunately, making the constructors private also prevents you from instantiating the class in a normal way, as a local or static variable. There is a more elegant technique to make classes non-derivable. As illustration, consider an exception type thrown by a binary tree container with unique keys — if a program attempts to insert an item with the same key, the container throws an exception of type CTreeKeyError. So here’s the exception class:

//***KEYERROR.H***
#ifndef _KEYERROR_H_
#define _KEYERROR_H_ 

#include <iostream>
#include <string>

template <class K, class T>
class CTreeKeyError
{
public:
   CTreeKeyError(const K& k, const T& t)
   : m_Key(k), m_Data(t),
     m_strMsg("Key already exists in binary tree.") {}
   void print() const
   {
      std::cout
         << "Data item could not be added to binary tree!"
         << std::endl;
      std::cout << "Reason: " << m_strMsg << std::endl;
      std::cout << "Key: " << m_Key << std::endl;
      std::cout << "Data: " << m_Data << std::endl;
   }

private:
   const K m_Key;
   const T m_Data;
   const std::string m_strMsg;
};

#endif

Every time an attempt is made to add a duplicate item to the tree, the container throws a CTreeKeyError object — this object contains the nature of the error, the data, and the key for error reporting. As it is currently defined, CTreeKeyError can be derived from. But let’s say that we would like CKeyTreeError to be a stand-alone class; we do not want to allow other classes to be derived from it. This restriction can be achieved by creating a helper class:

//***KEYERRORLOCK.H***
#ifndef _KEYERRORLOCK_H_
#define _KEYERRORLOCK_H_


// Usage: Make this a private virtual base class, and the 
// derived class can’t be further derived from.
//
class PriVirFinal
{
protected:
   PriVirFinal() { }
};

#endif

To make CTreeKeyError non-derivable, simply declare PriVirFinal as a private virtual base class:

// ...
#include "keyerrorlock.h"

template <class K, class T>
class CTreeKeyError : private virtual PriVirFinal
{
  // same as before
  // ...
};

PriVirFinal has a protected constructor, so it cannot be instantiated on its own. Since each most-derived class must initialize the virtual base, but only the immediately derived class can access the protected PriVirFinal constructor, no classes can be derived from CtreeKeyError — a further-derived class cannot initialze the virtual base. This technique is therefore very handy for making classes non-derivable.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.