PDA

View Full Version : C++ inheritance



yyiu002
29th June 2010, 03:20
I have read C++ guide line at google:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Inheritance

following lines I can't understand, please help.

All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead

xray2000
29th June 2010, 06:26
here is answer on your question:

Use composition when you can, private inheritance when you have to.

Normally you don't want to have access to the internals of too many other classes, and private inheritance gives you some of this extra power (and responsibility). But private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code.

Lykurg
29th June 2010, 10:31
It means you shouldn't do that:
class foo : private bar {};Instead do
class foo {
private:
bar *pointerToBar;
}

Zlatomir
29th June 2010, 11:38
Private inheritance is not recommended because it doesn't shape a "is-a" relationship (like OOP concepts say) private inheritance is more like composition, but it isn't that clear for others programmers, that read your code, what have you done in there (because most of us expect a "is-a" relationship between classes, when we see inheritance)

And for two classes you probably think that it's not a "big" deal, but what do you do when you need to use let's say 5 other classes? (imagine the code that private inherit from 5 other classes) the compiler doesn't care, it's for other programmers from your team (and for you, because if you read the code in a couple of months, for some update/re-factoring you won't find the code easy to read)

So this is a conceptual thing, it depends on what you want to model, if the new class (the one you are trying to create) will actually be a more specialized base class (the class that you use to build yours) you will use public inheritance (is-a relationship),
and when you want the new class to just use the other (or others classes) use composition (has-a relationship)