Use of “Public” in a derived class declaration?

帅比萌擦擦* 提交于 2019-11-28 18:18:31

The default is private inheritance. take this example:

class B { };
class D: B { };

uses private inheritance as its the default. This means that D gets all the protected and public fields and methods that B has (if we actually declared any), but can't be cast to a B. Therefore, this code fails:

void foo(B* argument) {}
foo(new D);                   //not allowed

If D publicly inherited from B, then a D could be cast to a B, and this function call would be fine.

The second difference is that all the protected and public members in B become private members in D.

What does this actually mean? Public inheritance means D IS_A B, but private inheritance means "is implemented in terms of". Inheriting D from B means you want to take advantage of some of the features in B, but not because D IS_A B or because there's any conceptual connection between B and D. :D

Without that 'public' 'Employee' would become a private base class of 'Manager'.

Classes declared with keyword 'class' have their members private by default, and have their base classes private by default.

Classes declared with keyword 'struct' have their members public by default, and have their base classes public by default.

In C++, inheritance is private by default. However, to any code using the Manager class, there appears to be almost no difference, since they have the same methods.

You won't be able to cast the Manager object to an Employee, though. You also won't be able to access the employees variable from within the Manager class.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!