0

Possible Duplicate:
Private/protected inheritance

Can you give me example for private inheritance in C++? As I understood, in this sort of inheritance, the public and the protected features of the parent don't filter throght the child, and only the public features of the child are visible.

Community
  • 1
  • 1
Tom
  • 673
  • 4
  • 12
  • 20

2 Answers2

2

Private Inheritance:
All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

If you are inclined to know about Inheritance & Access specifiers you can check out more at this answer I posted quite a while ago.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Private inheritance is usually used as a form of composition. It is not much different from having a member variable of the inherited type.

It means "implemented in terms of ..."

In some rare edge cases, it may be more efficient than having a member variable.

The most common usage of private inheritance I'm aware of is boost::noncopyable

Gilad Naor
  • 20,752
  • 14
  • 46
  • 53