As you’ll see in the next section, set and get member functions can validate attempts to modify private
data and control how that data is presented to the caller, respectively. These are compelling software engineering benefits.
If a data member were public
, any client of the class—that is, any other code that calls the class’s member functions—could see the data and do whatever it wanted with it, including setting it to an invalid value.
You might think that even though a client of the class cannot directly access a private
data member, the client can nevertheless do whatever it wants with the variable through public
set and get functions. You’d think that you could peek at the private
data (and see exactly how it’s stored in the object) any time with the public
get function and that you could modify the private
data at will through the public
set function.
Actually, set functions can be programmed to validate their arguments and reject any attempts to set the data to bad values, such as
a negative body temperature
a day in March outside the range 1 through 31
a product code not in the company’s product catalog, etc.
And a get function can present the data in a different form, while the actual data representation remains hidden from the user. For example, a Grade
class might store a grade
data member as an int
between 0 and 100, but a getGrade
member function might return a letter grade as a string
, such as "A"
for grades between 90 and 100, "B"
for grades between 80 and 89, etc. Tightly controlling the access to and presentation of private
data can greatly reduce errors, while increasing the robustness, security and usability of your programs.
Account
Object with Encapsulated DataYou can think of an Account
object as shown in Fig. 3.7. The private
data member name
is hidden inside the object (represented by the inner circle containing name
) and protected by an outer layer of public
member functions (represented by the outer circle containing getName
and setName
). Any client code that needs to interact with the Account
object can do so only by calling the public
member functions of the protective outer layer.
Generally, data members should be private
and member functions public
. In Chapter 9, we’ll discuss why you might use a public
data member or a private
member function.
Using public
set and get functions to control access to private
data makes programs clearer and easier to maintain. Change is the rule rather than the exception. You should anticipate that your code will be modified, and possibly often.