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的實作可以根據需求變化或錯誤回饋而不斷改進,無須改變用戶程式。