Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public and private inheritance in C++

As we know from the literature for the public inheritance the object of child class (sub-class) also can be considered as the object of base class (super-class). Why the object of the sub-class can’t be considered as an object of super-class, when the inheritance is protected or private?

like image 830
Narek Avatar asked Jan 06 '11 20:01

Narek


1 Answers

public inheritance serves the purpose of the is-a relationship. That is:

class A {};
class B : public A {};

Class B is a version of class A.

private inheritance serves the purpose of the has-a relationship. You can write almost any class using private inheritance using a container model instead:

class A {};
class B : private A {};

can be rewritten (and more often than not, should be rewritten for clarity):

class A {};
class B
{
private:
    A a;
};

protected inheritance is similar to private, but in reality should almost never be used (Scott Meyers and Herb Sutter both give reasons for this in their respective books).

like image 141
Zac Howland Avatar answered Oct 19 '22 03:10

Zac Howland