|
 |  | Section 9: Object Oriented Programming (OOP) | |
|
|
You are in Section 9 of 9, Article 9.2 of 9.7, Part 9.2.6 of 9.2.9
Accessors and Mutators
Accessors
One important advantage of using a class is that data can be encapsulated using the private class identifier. Data encapsulation ensures that only certain objects within a program have access to certain data.
Class methods must still be defined to be able to reference encapsulated data members. Methods that access data members, particularly private members, are called accessors.
An accessor is simply a method that is used to access (and only access!) some data member of a class. It is good programming practice to use accessors to access data members rather than simply declaring data members as public and using the dot ( . ) operator.
In our MyClass class specification, let's add a getData1() accessor:
In the above class specification, getData1() is an accessor method used to get the value of the data1 data member. It does nothing else but return the value of data1.
Mutators
While accessors access data members, mutators are methods used to modify (and only modify!) the value of a data member.
In our MyClass class specification, there is already a mutator: setData1(int d). setData1(int d) is a mutator used to modify the value of the data1 data member.
The following program demonstrates the user of class accessors and mutators. The main function consists of the following segment of code:
In the next part, we'll cover how to return objects from functions.
Read on for more...
Next: Returning Objects From Functions
You are in Section 9 of 9, Article 9.2 of 9.7, Part 9.2.6 of 9.2.9
[Back to Top]
|
|
|
|

|
|