Public and private inheritance in C++

2020-02-04 05:52发布

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?

7条回答
爷、活的狠高调
2楼-- · 2020-02-04 06:56

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).

查看更多
登录 后发表回答