hjk41的日志

Avatar

Effective C++ 42: Use private inheritance judiciously


class B{
public:
    void mf();
    ....
}
class D:private B{
    ...
}

void doSomething(B b){
    ...
}

B b;
D d;

doSomething(b);    // fine
doSomething(d);    // error! D can not be converted into B

b.mf();   // fine
d.mf();   // error! D::mf() is a private member function


In the code above, we can see that private inheritance differs from public inheritance in two ways:
First, objects of the derived class will generally not be converted into a base class object if the inheritance private.
Second, the public member functions of the base class will become private in the derived class.
So private inheritance means inheriting only the implementation, not the interface. And that makes private inheritance a good way to implement the relationship of "implemented-in-terms-of".

What is the difference between private inheritance and layering as ways of representing "implemented-in-terms-of"?
Well, using private inheritance you can access protected member functions of the base class in the derived class while you can't do that using layering.

So the conclusion is: private inheritance should be used to implement the relationship of "implemented-in-terms-of" when protected member functions get involved.

评论已关闭