Effective C++: discouraging protected inheritance? - c++

I was reading Scott Meyers' Effective C++ (third edition), and in a paragraph in Item 32: Make sure public inheritance is "is-a" on page 151 he makes the comment (which I've put in bold):
This is true only for public inheritance. C++ will behave as I've described only if Student is publicly derived from Person. Private inheritance means something entirely different (see Item 39), and protected inheritance is something whose meaning eludes me to this day.
The question: how should I interpret this comment? Is Meyers trying to convey that protected inheritance is seldom considered useful and should be avoided?
(I've read the question
Difference between private, public, and protected inheritance as well as C++ FAQ Lite's private and protected inheritance section, both of which explain what protected inheritance means, but hasn't given me much insight into when or why it would be useful.)

Some scenarios where you'd want protected:
You have a base class with methods where you know you never want to expose the functionality outside, but you know will be useful for any derived class.
You have a base class with members that should be logically used by any class that extends that class, but should never be exposed outside.
Thanks to multiple inheritance you can play around with base classes' inheritance type and construct a more diversed class with existing logic and implementation.
A more concrete example:
You could create a few abstract classes that follow Design Pattern logic, lets say you have:
Observer
Subject
Factory
Now you want these all to be public, because in general, you could use the pattern on anything.
But, with protected inheritance, you can create a class that is an Observer and Subject, but only protected factory, so the factory part is only used in inherited classes. (Just chose random patterns for the example)
Another example:
Lets say for example you want to inherit from a library class (not that I encourage it). Lets say you want to make you own cool extension of std::list<> or a "better" shared_ptr.
You could derive protectedly from the base class (which is designed to have public methods).
This will give you the option to use your own custom methods, use the class' logic, and pass the logic to the to any derived class.
You could probably use encapsulation instead, but inheritance follows the proper logic of IS A
(or in this case IS sort of A)

He isn't exactly discouraging protected inheritance, he just says that he hasn't found any good use for it. I haven't seen anyone either elsewhere.
If you happen to find a couple of really useful use cases, you might have material to write a book too. :-)

Yup, there aren't many uses for protected or private inheritance. If you ever think about private inheritance, chances are composition is better suited for you. (Inheritance means 'is-a' and composition means 'has-a'.)
My guess is that the C++ committee simply added this in because it was very easy to do and they figured, "heck, maybe someone will find a good use for this". It's not a bad feature, it doesn't do any harm, just that no one has found any real use for it yet. :P

Yes and no. I myself think that protected inheritance is a bad feature too. It basicly imports all the base class's public and protected members as protected members.
I usually avoid protected members, but on the lowest levels requiring extreme efficiency with a compiler with bad link-time optimization they are useful. But everything built on that shouldn't be messing with the original base class's (data) members and use the interface instead.
What I think Scott Meyer is trying to say, is that you can still use protected inheritance if it solves a problem, but make sure to use comments to describe the inheritance because it's not semantically clear.

I don't know if Meyers is advising us to refrain from using protected inheritance, but it seems you should avoid it if Meyers is on your team, because at least he won't be able to understand your code.
Unless your co-workers know C++ better than he does, you should probably also stay away from protected inheritance. Everybody will understand the alternative, i.e. using composition.
I can imagine however a case where it could make sense: You need access to a protected member in a class whose code you can't change but you don't want to expose an IS-A relationship.
class A {
protected:
void f(); // <- I want to use this from B!
};
class B : protected A {
private:
void g() { f(); }
};
Even in that case, I would still consider making a wrapper with public inheritance that exposes the protected base members with public methods, then compose with these wrappers.
/*! Careful: exposes A::f, which wasn't meant to be public by its authors */
class AWithF: public A {
public:
void f() { A::f(); }
};
class B {
private:
AWithF m_a;
void g() { m_a.f(); }
};

Related

What is the practical use of protected inheritance?

Public inheritance is easy.
A : public B means every A is a B. In most programming language, like vb.net and objective-c, this is the only type of inheritance.
Private inheritance is also easy but pointless
A : private B means A is implemented by B. However, that's pointless because that means A should contain B instead. Ownership means less coupling with no disadvantage.
Then we have protected inheritance.
Can anyone explain to me what the hell is that for? Some says it's an "as a relationship". I am still not very clear on that.
Does anyone has some sample cases where people uses protected inheritance in good pattern (and conscience) for actual productive use?
Private inheritance is also easy but pointless
A : private B means A is implemented by B. However, that's pointless because that means A should contain B instead. Ownership means less coupling with no disadvantage.
That you might not see reasons for private inheritance does not mean it's pointless.
There are several cases where private inheritance has its reasons. You are right in that at a first glance, private inheritance means has-a relationships just like aggregation, and that private inheritance has a (slightly) tighter coupling.
Reasons for favouring private inheritance over aggretations could be some of the following:
With private inheritance you inherit typedefs as well. In some cases (e.g. traits classes) inheriting privatly is just the alternative to re-typedef tons of typedefs in the base class.
In seldom cases you have to initialize a member before a "real" (i.e. public) base class. The only way to achieve that is by making that member a private base class inherited before the public base.
Some times you need access to protected members of a member. If you can't change the member class itself, you have to use private inheritance to get access to them.
If a member has no data members of its own, it still occupies space. Making it a private base class enables the empty base class optimization, diminuishing the size of your class' objects.
for even more points, see James' comments below
These reasons are obviously technical reasons, some might even say "hacks". However, such reasons exist, so private inheritance is not completely pointless. It is just not "pure OO style" - but C++ isn't a pure OO language either.
The reason for protected inheritance are quite simple once you understood the ones for private inheritance:
If you have reasons to inherit something privately and want to make those benefits (i.e. that would-be member of your class or the typedefs) accessible to derived classes, use protected inheritance. Obviously, private inheritance should be used scarcely, and protected inheritance even more so.
The main motivation for protected inheritance is orthogonality.
in all other contexts, you have three different access controls:
private, protected and public. Why should inheritance be
different? In practice, one could argue that there is no need
or use for protected access in general. That may be overstating
the case, but it is certain that a lot less is protected than
private or public.
Also, private inheritance is not at all pointless, and in fact,
corresponds to the original use of inheritance. As soon as the
base class doing the implementing uses virtual functions which
the derived class has to overload, containment cannot be used.

Without using `protected`, how the subclass can effectively use the variables defined in base class

Bjarne Stroustrup once said that he can address most of the tasks with ONLY private or public member variables and he seldom uses protected member variables in his design. I have heard similar arguments in other places. Here is an example,
class BaseClass
{
...
private:
int m_iAge;
double m_dSalary;
string m_strName;
bool m_bGender;
}
class SubClass : public BaseClass
{
...
}
Given the above class design, how the subclass SubClass can use the variables defined in BaseClass?
Question1> Why we should prefer to having private rather than protected variables? Is it the reason that the BaseClass can hide the implementation detail and make it easy for further improvement?
Question2> In order to let the SubClass access the variable defined in BaseClass, it seems to me that we have to define public access(get/set). However, getter/setter are evil! So the second choice is to define protected access(get/set). Any better idea?
Thank you
Bjarne's point is that generally the derived class shouldn't access the variables of the base class -- doing so frequently leads to maintenance problems. And no, changing it to use get/set (accessor/mutator) functions isn't an improvement.
Ask yourself - why would the derived class ever change the value of m_bGender? Or m_iAge? Doesn't the base class already handle these values correctly?
See, there is generally no need to have direct access to the internals of the base class. So we make them private, and use the class' public interface.
In some very rare cases, there might also be one or two protected functions, if derived classes need some special interface. But that is unusual. If derived classes have different behaviour, we more often use virtual functions for that.
I think the rationale for this claim is that in many situations, subclassing doesn't often change the behavior of the existing (inherited fields), but rather one adds fields and adds new methods that manipulate the new fields.
If you are looking for a way to manipulate inherited members w/o protected, you can, in the base class, make the derived class a friend. You would have to know it ahead of time, though.
The only main reason to use private over protected members is if they indeed are not required in child implementations. That's why we have protected members, because there are cases where the child class does need direct access to members of a parent class. I think Stroustrup is referring to a design whereby there is little need to access parent members in the first place, and child classes simply build upon the functionality of their parent rather than modify the functionality of their parent.
However, getter/setter are evil!
Why so? Getters and setters are an important part of OOP from my experience. There are good reasons to make an interface with a class, rather than access its variables directly.

multiple inheritance is convenient?

i want to implement an Algorithm class which uses some utility classes.
but one class may need member variable or function of other utility class. So instead of
composition is it better to use inheritance as below ?
class A{
public:
void setA(int var){ a = var;}
int a;
};
class B{
public:
void foo(int var){
if (var==1){
//bla bla...
}else{
//bik bik...
}
};
class Algo : public A , public B{
public :
void run(){
setA(1);
foo(a);
}
};
Your class Algo should only inherit from A and B if it is a true IS-A relationship to A and B. If you are just wanting to use functionality from A or B, consider composition instead (or at least private inheritance).
For example, if I want to create a class, and that class needs to do some logging, then my class HAS-A logger, but it's not the case that it IS-A logger. Thus I wouldn't want to inherit from logger, but use composition instead.
In your case it doesn't make sense to use inheritance because Algo isn't a A or B, it merely uses them.
Inheritance is meant to express an "is a" relationship and should adhere to the Liskov substitution principle. Can you say Algo is an A and Algo is a B? In general I feel it's a bad idea for a derived class to muck with the base classes private variables (you may set them as protected but they should probably be private). You can always write getters and setters. You can get into trouble with multiple inheritance in so many ways and I think your approach while convenient now will lead you to program in a less maintainable way. I try to reserve inheritance for when I need to treat classes polymorphically, in most other cases I prefer composition.
I like this concept of inheritance:
Commonly thought of as a way to "reuse existing code" by creating a new class that inherits from another existing class. This way you can extend the functionality of an existing class w/o touching the existing class's code. But Herb Sutter has a bit of a different take on the use of inheritance--"Inherit, not to reuse, but to be reused. Don't inherit publicly to reuse code (that exists in the base class); inherit publicly in order to be reused (by existing code that already uses base objects polymorphically)." [C++ Coding Standards, p. 64]. He also says "In correct inheritance, a derived class models a special case of a more general base concept." [ibid, p. 66]
http://cpp.strombergers.com/
so if you don't need to reuse code polymorphically, or to make more special case for base, better use a composition.
Don't pick inheritance over composition as long as you do not need polymorphism. In your case, as you don't have and virtual functions in classes A and B that needs to be changed in class Algo, composition may be a better design choice.

How often is non-public C++ inheritance used in practice? [duplicate]

This question already has answers here:
Closed 11 years ago.
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.
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:
I would like to trigger the Empty Base Optimization if possible (usually, in template code with predicates passed as parameters)
I would like to override a virtual function in the class
In 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
Since private inheritance has as its only known use implementation inheritance, and since this could always be done using containment instead (which is less simple to use, but better encapsulates the relationship), I'd say it's used too often.
(Since nobody ever told me what protected inheritance means, let's assume nobody knows what it is and pretend it doesn't exist.)
Sometimes inheriting the classes which are neither having any virtual functions nor a virtual destructor (e.g. STL containers), you may have to go for non-public inheritance. e.g.
template<typename T>
struct MyVector : private std::vector<T>
{ ... };
This will disallow, handles (pointer or reference) of base (vector<>) to get hold of derived class (MyVector<>):
vector<int> *p = new MyVector<int>; // compiler error
...
delete p; // undefined behavior: ~vector() is not 'virtual'!
Since, we get compiler error at the first line itself, we will be saved from the undefined behavior in the subsequent line.
If you are deriving from a class without a virtual destructor then Public inheritance leads to a chance that users of the class can call delete on a pointer-to-base, which leads to undefined behaviour.
In such an scenario it makes sense to use private Inheritance.
Most common example of this is to derive privately from STL containers which do not have virtual destructors.
C++FAQ has an excellent example of Private Inheritance which extends to many real live scenarios.
A legitimate, long-term use for private inheritance is when you want to build a class Fred that uses code in a class Wilma, and the code from class Wilma needs to invoke member functions from your new class, Fred. In this case, Fred calls non-virtuals in Wilma, and Wilma calls (usually pure virtuals) in itself, which are overridden by Fred. This would be much harder to do with composition.
Code Example:
class Wilma {
protected:
void fredCallsWilma()
{
std::cout << "Wilma::fredCallsWilma()\n";
wilmaCallsFred();
}
virtual void wilmaCallsFred() = 0; // A pure virtual function
};
class Fred : private Wilma {
public:
void barney()
{
std::cout << "Fred::barney()\n";
Wilma::fredCallsWilma();
}
protected:
virtual void wilmaCallsFred()
{
std::cout << "Fred::wilmaCallsFred()\n";
}
};
Non-public (almost always private) inheritance is used when inheriting
(only) behavior, and not interface. I've used it mostly, but not
exclusively, in mixins.
For a good discussion on the topic, you might want to read Barton and
Nackman (Scientific and Engineering C++: An Introduction with Advanced
Techniques and Examples, ISBN 0-201-53393-6. Despite the name, large parts of the book are
applicable to all C++, not just scientific and engineering
applications. And despite its date, it's still worth reading.)

Private inheritance and composition, which one is best and why? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
suppose i have a class engin and i inherit a class car from engin class
class engin
{
public:
engin(int nobofcylinders);
void start();
};
class car:private engin
{
public:
car():e(8){}
void start()
{
e.start();
}
private:
engin e;
};
now the same can be done by the composition, the question is which approch would be best and is mostly used in programming, and why???????
Composition is to be preferred for two main reasons:
the thing(s) being composed can have names
you can compose more than one thing of the same type
I prefer to think of inheritance as derived is a kind of base, that basically means public inheritance. In case of private inheritance it more like derived has a base, which IMHO doesn't sound right, because that's IMHO the work for composition not inheritance of any kind. So, since private inheritance and composition essentially mean same thing logically, which to choose? With the example you posted, I'd most certainly go for composition. Why? I tend to think of all kinds of inheritance as a kind of relationship, and with the example you posted, I can't think of a situation where I could say a car is kind of an engine, it simply isn't. It's indeed like a car has an engine, so why would a car inherit from an engine? I see no reason.
Now, indeed there are cases where it's good to have private inheritance, namely boost::noncopyable, with it's ctor/dtor being protected, you'd have hard time instantiating it, and indeed since we want our class to have a noncopyable part, that's the only way to go.
Some style guides (e.g. google c++ style guide) even recommend to never use private inheritance, for reasons similar to what I already written - private inheritance is just a bit confusing.
If you want to compare private inheritance with composition, read http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.3. I don't think private inheritance is good.
A Car has-an Engine, but a Car is-not-an Engine, so it should be better done with composition.
Inheritence is useful for "is-a" relationships, e.g. a Bus is-a Car, a Car is-a vehicle, etc.
Composition is useful for "has-a" relationships, e.g. a Car has Wheel-s, a Car has-an Engine, etc.
So a logical code should be like
class Car : public Vehicle {
Engine engine;
Wheel wheels[4];
...
};
Private inheritance, despite the name, isn’t really inheritance – at least not from the outside (of the class), where it matters.
For that reason, different rules apply. In C++, private inheritance is said to model an “is implemented in terms of” relationship. Thus, a priority queue which is implemented in terms of a heap, could look like this:
template <typename T, typename Comp = std::less<T> >
class priority_queue : private heap<T, Comp> {
// …
};
Personally, I don’t see the advantage of this pattern, and Neil has already stated that in most cases, composition actually has the advantage over private inheritance.
One advantage exists, though: since it’s such an established pattern, the meaning of a private inheritance is immediately clear to a seasoned C++ programmer; the above code would tell them that the priority queue is implemented in terms of a heap – which wouldn’t be obvious if the class just happened to use a heap as one of its members.
Private inheritance tends to get used in C++ primarily for policy classes. The classical example is allocators, which determine how a container class manages storage internally:
template <typename T, typename A = std::allocator<T> >
class vector : private A {
// …
};
No harm done. But once again, this could also have been done using composition.
Usually, composition is to be preferred (others gave the major reasons), but private inheritance allows things which can't be done by composition:
zero-size base class optimization (a base class of size zero will not increase the size of a class, a member of size zero will), that't the reason behind its use for policy classes which often have no data members
controlling initialization order so that what is composed is initialized before a public base
overriding a virtual member in what is composed
with private virtual inheritance, ensuring that there is only one composed thing even if one do it in several bases
Note that for the later two uses, the fact that the base class exist can be observed in a descendant.
Composition is used more than private inheritance. The general rule I follow and would recommend is that unless you have a specific reason to use private inheritance you should use composition.
Composition has many benefits over private inheritance:
You can have more than one instance of a particular class.
You don't pollute your class' namespace with a bunch of private functions that don't make sense for your class.
You can give names to the parts of your object
Your class is less coupled to the classes it's composed of than it is to a class it inherits from
If you discover you need to swap out an object that you've included by composition during the lifetime of your object, you can, with private inheritance you're stuck.
There are a lot of other benefits to composition. Basically, it's more flexible and cleaner.
There are reasons to use private inheritance though. They are very specific reasons, and if you think they apply, you should think carefully about your design to make sure you have to do it that way.
You can override virtual functions.
You can get access to protected members of the base class.
You need to pass yourself to something that wants an object of the class you're inheriting from (this usually goes hand-in-hand with overriding virtual functions).
And there are a few rather tricky ones as well:
If you use composition for a class that has 0 size, it still takes up space, but with private inheritance it doesn't.
You want to call a particular constructor for a virtual base class of the class you're going to privately inherit from.
If you want to initialize the private base before other base classes are initialized (with composition, all the variables in your class will be initialized after all your base classes are).
Using private virtual inheritance to make sure there's only one copy of a thing even when you have multiple base classes that have it. (In my opinion, this is better solved using pointers and normal composition.)
Private inheritance means
is-implemented-in-terms of. It's
usually inferior to composition, but
it makes sense when a derived class
needs access to protected base class
members or needs to redefine
inherited virtual functions.
Unlike composition, private
inheritance can enable the empty base
optimization. This can be important
for library developers who strive to
minimize object sizes.
Scott Meyers "Effective C++" Third Edition.
Base classes are evil.
In my mind, good OO design is about encapsulation and interfaces. The convenience of base classes are not worth the price you pay.
Here's a really good article about this:
http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html