// Stopping of class inheritance with condition that object creation should be allowed
// in C++ can be done by means of private constructor with virtual inheritance and friend class
#include<iostream>
using namespace std;
class Final;
class Helper
{
Helper() // private constructor
{
cout << "Constructor of Helper class to simulate Final class. ";
};
friend class Final; // friend class
};
class Final : virtual Helper // virtual inheritance
{
public:
Final() // this constructor can call the private constructor of Helper class because Final and Helper are friends
{
cout << "Constructor of Final class which cannot be inherited but instantiated. ";
};
};
// the code below shows inheritance attempt and throws an error if uncommented
// class Child : public Final
// {
// public:
// Child() // this constructor tries to call the private constructor of Helper and cannot
// {
// cout << "Constructor of Child class which is tried to be inherited. ";
// };
// };
int main()
{
Final f; // can be instantiated
//Child c; // cannot be inherited
return 0;
}
Comments
Leave a comment