
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Simulating Final Class in C++
In Java or C#, we can use final classes. The final classes are special type of class. We cannot extend that class to create another class. 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