Why we not go for private and protected Inheritance in c++ ?

class A
{
protected:
void k();

};
Class B : private A
{
void k();
};

//What is wrong in this code of c++, Why we not go for private and protected Inheritance in c++ ?
Last edited on
for inheritance use public A
dont use private or protected thats why they r protected and private also there is a way to inherit protected

look at the link:
http://www.cplusplus.com/doc/tutorial/inheritance/
@Caset I don't know what you think you know, but that's not how private and protected inheritance work. ;)

The three kinds of inheritance are all useful, but private and protected just have less common use.
Last edited on
@L B wow thx for the info. i was remebering wrong if so. srry
@ L B ... my question was Why we not go for private and protected Inheritance in c++ ? what's the disadvantage ?
What is wrong in this code of c++

Apart from the misspelling of private and protected? (the capital P would confuse the compiler!)

Why we not go for private and protected Inheritance in c++ ?

They are not used very often as there are normally better ways to achieve the same aim.

As you no doubt know, public inheritence is about is-a relationships. But this relies on the derived class inheriting the interface (i.e. public methods) so the outside world can see the class behaves like its parent class or classes.

Neither private nor protected inheritence add to the the public interface of a class, so they can not be used to inherit bevaviour, only implementation. That is, they represent an (e.g.) implemented-using relationship.

As you're just using the code internally, there's usually no need to inherit. Instead you can use composition (i.e. you have a class member which does the work), which is cleaner from an object pointed view as it has looser coupling.

There are cases when private inheritence is better than composition (as it makes things simpler), or is actually required, but they are the exceptions to the general rule.

Andy

This article discusses the issue, with examples of when non-public inheritence is useful:

Uses and Abuses of Inheritance, Part 1
http://www.gotw.ca/publications/mill06.htm

See item 34 "Prefer composition to inheritence" in the book "C++ Coding Standards" by Sutter and Alexandrescu
Last edited on
Well, I was going to link you to Marshall Cline's C++FAQ-Lite, where he does a very good job of explaining them in his section on private and protected inheritance... but he seems to be messing with it right now and the links are all broken.
@ Duoas and @ andywestken (3106) answer these as well kindly !
http://www.cplusplus.com/forum/general/111310/
http://www.cplusplus.com/forum/general/111245/
Topic archived. No new replies allowed.