Rationale for difference in “default” access-specifier for a base class

…衆ロ難τιáo~ 提交于 2019-12-11 07:27:39

问题


I know that there're few differences between struct and class in C++. I also understand the reason(s) for few of the difference(s). Like this one,

  • Members of struct are public by default; members of class are private by default. The reason why members of struct are public by default, is to make C++-struct compatible with C-struct. And the reason why member of class are private by default, is to introduce the concept of data encapsulation (i.e enforcing object-oriented principles/techniques/etc).

What I don't understand is this, quoting the Standard $11.2/2 [class.access.base]

In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

What is the rationale for this twist and anti-uniformity? Why is this difference needed?

Example from the Standard,

class B {  };
class D1 : private B {  };
class D2 : public B { };
class D3 : B { };         //B private by default
struct D4 : public B { };
struct D5 : private B { };
struct D6 : B { };        //B public by default
class D7 : protected B { };
struct D8 : protected B { };

Here B is a public base of D2, D4, and D6, a private base of D1, D3, and D5, and a protected base of D7 and D8.


EDIT

Some of you might say, this difference makes sense given the default access for struct and class being different (the difference given in the bullet-point above). But I think, inherited-struct altogether is incompatible with C-struct (which doesn't support inheritance), no matter how you derive it. I may be wrong though. That is why I'm seeking good explanations, possibly with examples! :-)


回答1:


I'm not sure why you think it's a twist, you have consistency with member sub-objects and base class sub-objects. They are both public for classes declared with struct and private for classes declared with class. Simple and easy to remember.




回答2:


Doesn't this make sense given the default access for struct and class being different? (as in your first bullet point)

If you inherit from a struct (which by default is public) then without specifying an access modifier, you are implying public inheritenance whereas If you inherit from a class (which by default is private) then without specifying an access modifier, you are implying private inheritenance.

Did I miss something in your question?



来源:https://stackoverflow.com/questions/4427244/rationale-for-difference-in-default-access-specifier-for-a-base-class

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