Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   How to prevent your class getting inherited (http://www.go4expert.com/articles/prevent-class-getting-inherited-t16096/)

jayaraj_ev 6Feb2009 12:57

How to prevent your class getting inherited
 
When you plan to design a Class for which you feel that it should not be inherited further by any other class then...Here is a tip : Use of Virtual Private Inheritance

Code:

#include <iostream>

using namespace std;

class Base
{
  protected:
    Base()
    {
      cout<<"Base::Base"<<endl;
    }
};

class Dervied : virtual private Base
{
  public:
    Dervied()
    {
      cout<<"Dervied::Dervied"<<endl;
    }
};

class Client : public Dervied
{
  public:
    Client()
    {
      cout<<"Client::Client"<<endl;
    }
};

int main(void)
{
  Client c;
  return 0;
}

Here Derived class cannot be inherited by any other class.But when our client class tries to inherit we get a Error :
In constructor `Client::Client()':
error: `Base::Base()' is protected


The reason is simple when ever you inherit a class virtually then you should call the constructor of Base explicity on good design.

asadullah.ansari 6Feb2009 17:11

Re: How to prevent your class getting inherited
 
Nice one...
You can also get this concept in this thread
http://www.go4expert.com/showthread.php?t=8278

shabbir 4Mar2009 09:56

Re: How to prevent your class getting inherited
 
Nominate this article for Article of the month for February 2009

shabbir 17Mar2009 12:17

Re: How to prevent your class getting inherited
 
Vote for this article for Article of the month February 2009


All times are GMT +5.5. The time now is 21:07.