Course Content
C++ OOP
C++ OOP
Accessor and Mutator Methods
Encapsulation also involves restricting direct access to some of an object's components, which is where accessor and mutator functions come into play. Accessor and mutator functions more commonly known as getters and setters, are public methods that provide controlled access to the private data members of a class.
- Accessor Functions (Getters): These functions allow reading the values of private data members without modifying them. They are crucial for obtaining the state of an object while keeping the data members hidden and protected.
- Mutator Functions (Setters): These functions enable the modification of private data members' values. They provide a controlled way to change the state of an object. By using setters, it's possible to implement validation logic to ensure that only valid data is assigned to the data members.
Ways to use
The primary function of getters and setters is to manage access to a class's members, thereby minimizing the likelihood of errors caused by direct manipulation. For instance, they enable you to restrict the assignment of excessively large values to certain properties.
main
#include <iostream> class Heater { public: void setPower(int value) { power = value > 10 ? 10: value; } int getPower() { return power; } private: int power; }; int main() { Heater heater; heater.setPower(7); std::cout << heater.getPower(); }
Note
In the example above we limit the power of the heater by value 10, you can set it more than that.
Thanks for your feedback!