How to prevent class inheritance in C++

C++Server Side ProgrammingProgramming

Here we will see how to prevent inheritance in C++. The concept of preventing the inheritance is known as final class.

In Java or C#, we can use final classes. In C++ there are no such direct way. Here we will see how to simulate the final class in C++.

Here we will create one extra class called MakeFinalClass (its default constructor is private). This function is used to solve our purpose. The main Class MyClass can call the constructor of the MakeFinalClass as they are friend classes.

One thing we have to notice, that the MakeFinalClass is also a virtual base class. We will make it virtual base class because we want to call the constructor of the MakeFinalClass through the constructor of MyDerivedClass, not MyClass (The constructor of a virtual base class is not called by the class that inherits from it, instead of the constructor that is called by the constructor of the concrete class).

Example

#include <iostream>
using namespace std;
class MyClass;
class MakeFinalClass {
   private:
      MakeFinalClass() {
         cout << "This is constructor of the MakeFinalClass" << endl;
      }
      friend class MyClass;
};
class MyClass : virtual MakeFinalClass { //this will be final class
   public:
      MyClass() {
         cout << "This is constructor of the final Class" << endl;
      }
};
//try to make derived class
class MyDerivedClass : MyClass {
   public:
      MyDerivedClass() {
         cout << "Constructor of the Derived Class" << endl;
      }
};
main() {
   MyDerivedClass derived;
}

Output

In constructor 'MyDerivedClass::MyDerivedClass()':
[Error] 'MakeFinalClass::MakeFinalClass()' is private

We can create the objects of the MyClass as this is friend of the MakeFinalClass, and has access to its constructors.

Example

#include <iostream>
using namespace std;
class MyClass;
class MakeFinalClass {
   private:
      MakeFinalClass() {
         cout << "This is constructor of the MakeFinalClass" << endl;
      }
      friend class MyClass;
};
class MyClass : virtual MakeFinalClass { //this will be final class
   public:
      MyClass() {
         cout << "This is constructor of the final Class" << endl;
      }
};
main() {
   MyClass obj;
}

Output

This is constructor of the MakeFinalClass
This is constructor of the final Class
raja
Published on 08-May-2019 12:12:08
Advertisements