Tuesday, July 31, 2012

how to restrict base class from inheritance!!

In CPP there is a way to restrict the base class from Inheritance. That means , Base class will not allow to create the new derived classes. We can achieve this by making constructor private in the class.
How it works: The basic logic behind this is C++ class access specifier. Derived classes are not allowed to access the private data of the base class. So to create the instance/object of the derived class, it needs base class constructor. So if you make base constructor private, when derived class trying to access the base constructor, it will fail. See the sample code below.

#include<iostream>
using namespace std;

class base
{
//public:
    base()
    {
        cout<<"base constructor\n";
    }
};

class derive:base
{
public:
    derive()
    {
        cout<<"derived constructor\n";
    }
};

main()
{
    derive d;
}

In the above code,  In the base class construtor is private and we derived a new class derive. It looks good till now. But the problem is in main() where we created the instance/object of the derive class. Because of base constructor is private, it will throw the below error.

restrict.cpp: In constructor 'derive::derive()':
restrict.cpp:7: error: 'base::base()' is private
restrict.cpp:17: error: within this context

No comments:

Popular Posts