Is there any practical use of private inheritance ?

Started by
2 comments, last by Tibetan Sand Fox 11 years, 2 months ago

Hello there.

As asked in topic I wonder if there is any sense of using private inheritance as this:


class Foo
{

public:
    void Bar();
};

class Derived : private Foo
{
};

pretty much means the same as that:


class Foo
{

protected:
    void Bar();
};

class Derived : public Foo
{
};

Only difference I see is that I choose if I want public elements of Foo class to be inherited as private or if I'd rather like to inherit them as public, but is that flexibility helpful in any way ? I mean, in my opinion private inheritance could possibly just bring mess and chaos to code, but maybe some people in here had an occasion to find that solution helpful ? Thank you very much in advance.

Advertisement
There is a FAQ on that.

It is one of many c++ features that are rarely needed but nice to have.

It can be used as a channel to send messages between classes: the base class calls a protected pure virtual function and the child class calls a protected base function.

It can be used for containing things where only the containing object knows the association.

Uses are very uncommon, you may never need it. But if you do need it, it is there.

Technically, private inheritance should be used for "implementation inheritance" and public used for "interface inheritance".

For example, many of my classes inherit from NonCopyable (below) in order to disable their copy-constructor and assignment operator.


class NonCopyable
{
public:
	NonCopyable(){}
private:
	NonCopyable( const NonCopyable& );
	NonCopyable& operator=( const NonCopyable& );
};

class Example : NonCopyable
{
public:
	Example(int i=0) : foo(i) {}
private:
	int foo;
};

Now, I could've written "class Example : public NonCopyable", and the code would work just the same... but public inheritance is designed to express an "is a" relationship between classes, and in this case, I'm not trying to say that Example is a NonCopyable, I'm just trying to say that I want to re-use the implementation of NonCopyable inside Example.

With public-inheritance / interface-inheritance / is-a, you're promising to follow certain OOP rules, such as the LSP, where an algorithm that works on the base-class / interface type, will continue to work as expected if any derived type is used instead. In this case, I don't want anyone to go and write functions that take a "NonCopyable*" as input, so that detail is hidden with private/implementation inheritance instead.

Thank you very much for the answers. That's just what I needed to know. I did some research on my own about the private inheritance and I found quiet few more of the uses of that feature. Actually I could have done that before asking the question, but well, without the questions forum would be quiet empty happy.png

//edit: +1'ed as promised.

This topic is closed to new replies.

Advertisement