Class Design and Protected Members

C++ Primer 4/e在Defining Base and Derived Classes这个地方有一个关键概念:‘In the absence of inheritance, a class has two kinds of users: members of the class itself and the users of that class. This separation between kinds of users is reflected in the division of the class into private and public access levels. Users may access only the public interface; class members and friends may access both the public and private members.

Under inheritance, there is now a third kind of user of a class: programmers who will define new classes that are derived from the class. The provider of a derived class often (but not always) needs access to the (ordinarily private) base-class implementation. To allow that access while still preventing general access to the implementation, an additional access label, protected, is provided. The data and function members in a protected section of a class remain inaccessible to the general program, yet are accessible to the derived class. Anything placed within a private section of the base class is accessible only to the class itself and its friends. The private members are not accessible to the derived classes.

When designing a class to serve as a base class, the criteria for designating a member as public do not change: It is still the case that interface functions should be public and data generally should not be public. A class designed to be inherited from must decide which parts of the implementation to declare as protected and which should be private. A member should be made private if we wish to prevent subsequently derived classes from having access to that member. A member should be made protected if it provides an operation or data that a derived class will need to use in its implementation. In other words, the interface to the derived type is the combination of both the protected and public members.’

中文版的这样写:‘当不存在继承时,class有两种使用者:class成员函式和class用户。这两者的区别反映在class内部的private和public存取级别上。class用户只能存取public介面,class成员函式及其friends可存取public和private成员。

有了继承之后,class多出第三种使用者:derived classes。Derived class经常(但非总是)需要存取base class的实作部份(一般为private)。为准许此种行为并避免一般人存取时作部份,C++另外提供了一个存取级别protected。此级别的成员函式和成员变数不能被一般程式取用,但可被derived class存取。至于base class的private区段内的任何东西只能被class自身及其friends取用,无法被derived classes存取。

设计base class时“成员是否该为public”的判断准则并未改变:介面函式应该设计为public,资料通常不该是public。设计base class时还必须决定哪些实作应宣告为protected,哪些应宣告为private。如果想避免让derived classes存取某成员,那个成员就该是private。如果某成员提供的是“derived class需要用到的操作成员或资料”,那个成员就该是protected。换句话说,开放给derived class的是“protected 和public成员的联集”。’

联集?这一段英文是the interface to the derived type is the combination of both the protected and public members,不是在讲介面是protected跟public的组合吗?怎跟联集扯上关系?嗯!可能没有跟数学的联集有关系,不过还是很让人疑惑?