Item 22: Declare data members private.

  1. 1. Part 4: Designs and Declarations
  2. 2. Things To Remember
  3. 3. Key Words
  4. 4. Key Points
  5. 5. Code

This article is one of <Effective C++> reading notes.

Part 4: Designs and Declarations

Item 22: Declare data members private.


Things To Remember

  • Declare data members private. It gives clients syntactically uniform access to data, affords fine-grained access control, allows invariants to be enforced, and offers class authors implementation flexibility.
  • protected is no more encapsulated than public.

Key Words

syntactic consistency (语法一致性):

Ways to facilitate the correct use include consistency in interfaces and behavioral compatibility with build-in types. [Item 18]

fine-grained access control:

Coarse-grained vs. fine-grained access control.

class invariants:

A class invariant is an invariant used to constrain objects of a class. Methods of the class should preserve the invariant. The class invariant constrains the state stored in the object.

Key Points

Suppose we have a protected data member, and we eliminate it, then all the derived classes that use it might be broken now.

Unencapsulated means unchangeable, especially for classes that are widely used. So from an encapsulation point of view, there are really only two access levels: private (which offers encapsulation) and everything else (which doesn’t). [see alse <The Design and Evolution of C++>]

比 private 更彻底的方案是把私有部分全部放在一个私有的内部类中,并把私有类的定义从公开的头文件里删掉,只被实现所见。[Item 31]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
// Fine-grained access control
class AccessLevels {
public:
trueint getReadOnly() const { return readOnly; }
void setWriteOnly(int value) { writeOnly = value; }
void setReadWrite(int value) { readWrite = value; }
int getReadWrite() const { return readWrite; }
private:
trueint noAccess; // no access to this int int readOnly;
true// read-only access to this int
trueint writeOnly; // write-only access to this int
trueint readWrite; // read-write access to this int
};