Possible Duplicate:
When should I use C++ private inheritance?
I wanted to make this community-wiki but don't see the button... can someone add it?
I can't think of any case I've derived from a class in a non-public way, and I can't recall off-hand seeing code which does this.
I'd like to hear real-world examples and patterns where it is useful.
public, protected and private inheritance in C++ protected inheritance makes the public and protected members of the base class protected in the derived class. private inheritance makes the public and protected members of the base class private in the derived class.
Multiple Inheritance in C++ allows a derived class to inherit more properties and characteristics since it has multiple base classes. It proves to be beneficial to design various design patterns.
The private inheritance allows access to the protected members of the base class. The private inheritance allows Car to override Engine's virtual functions.
We use inheritance in C++ when both the classes in the program have the same logical domain and when we want the class to use the properties of its superclass along with its properties.
Your mileage may vary...
The hard-core answer would be that non-public inheritance is useless.
Personally, I use it in either of two cases:
virtual
function in the classIn either cases, I thus use private
inheritance because the inheritance itself is an implementation detail.
I have seen people using private
inheritance more liberally, and near systematically, instead of composition when writing wrappers or extending behaviors. C++ does not provide an "easy" delegate syntax, so doing so allow you to write using Base::method;
to immediately provide the method instead of writing a proper forwarding call (and all its overloads). I would argue it is bad form, although it does save time.
If you chose inheritance for developing a wrapper, private inheritance is the way to go. You no longer need or want access to your base class' methods and members from outside your wrapper class.
class B;
class A
{
public:
A();
void foo(B b);
};
class BWrap;
class AWrap : private A
{
public:
AWrap();
void foo(BWrap b);
};
//no longer want A::foo to be accessible by mistake here, so make it private
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With