Benefits of Data Abstraction and Encapsulation

C++ Primer 4/e在Class Definitions and Declarations这个地方有一个关键观念:‘Data abstraction and encapsulation provide two important advantages:

  • Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.

  • The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data are public, then any function that directly accesses the data members of the old representation might be broken. It would be necessary to locate and rewrite all those portions of code that relied on the old representation before the program could be used again.

Similarly, if the internal state of the class is private, then changes to the member data can happen in only a limited number of places. The data is protected from mistakes that users might introduce. If there is a bug that corrupts the object’s state, the places to look for the bug are localized: When data are private, only a member function could be responsible for the error. The search for the mistake is limited, greatly easing the problems of maintenance and program correctness.

If the data are private and if the interface to the member functions does not change, then user functions that manipulate class objects require no change.’


  • Classes内部可以不受用户级(user-level)错误的影响,否则那些错误可能会破坏物件状态。
  • Classes的实作可以根据需求变化或错误回馈而不断改进,无须改变用户程式。