Simulating final class in C++

Hello friends, in this tutorial, we will learn how we can simulate a final class in C++. In Java, we use the final keyword and in C# we can use the sealed keyword to make a non-extendable class. But in C++, there is no direct way to do that. To make a class final in C++, we follow these steps:

  • Create an extra class MakeitFinal with a private constructor within it.
  • Let’s say the class that we want to make final is FinalClass. Make this class a friend of the MakeitFinal class.
  • Declare MakeitFinal class as a virtual base class for the FinalClass.
  • Now, the constructor of FinalClass can call the constructor of MakeitFinal.

If we try to inherit this FinalClass, the compiler will throw an error. Have a look at the below example to better your understanding of the concept.

#include <iostream>

class FinalClass;

class MakeitFinal{
  private:
    MakeitFinal(){
      std::cout << "Constructor of MakeitFinal class.\n";
    }
  friend class FinalClass;
};

class FinalClass : virtual MakeitFinal{
  public:
    FinalClass(){
      std::cout << "Constructor of FinalClass class.\n";
    }
};

class Child : public FinalClass{
  public:
    Child(){
      std::cout << "Constructor of Child class.\n";
    }
};

int main()
{
  Child c;
  return 0;
}

Output:

In constructor 'Child::Child()':
[Error] 'MakeitFinal::MakeitFinal()' is private

The above program throws an error because we are trying to inherit from the FinalClass. That means we have successfully created our final class which is not inheritable. Let’s create an object of this FinalClass and see if everything works fine.

#include <iostream>

class FinalClass;

class MakeitFinal{
  private:
    MakeitFinal(){
      std::cout << "Constructor of MakeitFinal class.\n";
    }
  friend class FinalClass;
};

class FinalClass : virtual MakeitFinal{
  public:
    FinalClass(){
      std::cout << "Constructor of FinalClass class.\n";
    }
};

int main()
{
  FinalClass f;
  return 0;
}

Output:

Constructor of MakeitFinal class.
Constructor of FinalClass class.

Thank you.

Also read: Assert and static_assert in C++

Leave a Reply

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