Contenido del Curso
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) are functions that 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.
getter
class Example { public: int get_member() { return member; } private: int member; };
Mutator Functions (Setters) are functions that 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.
setter
class Example { public: void set_member(int value) { member = value; } private: int member; };
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. You can limit the power of the heater by value 10
, you can set it more than that.
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(); }
¡Gracias por tus comentarios!