C++ - defenition - private inheritance [duplicate]
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.
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.
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
精彩评论