1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to prevent your class getting inherited

Discussion in 'C++' started by jayaraj_ev, Feb 6, 2009.

  1. jayaraj_ev

    jayaraj_ev New Member

    Joined:
    Aug 29, 2007
    Messages:
    20
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Software engineer
    Location:
    Bangalore
    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.
     
  2. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,285
    Likes Received:
    364
    Trophy Points:
    83
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,285
    Likes Received:
    364
    Trophy Points:
    83

Share This Page