> For the complete documentation index, see [llms.txt](https://codexpress.gitbook.io/welcome-to-codexpress/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codexpress.gitbook.io/welcome-to-codexpress/object-oriented-programming/c++-oops/encapsulation/getters-and-setters.md).

# Getters & Setters

Encapsulation often involves the use of getter and setter methods as a way to control access to an object's private data members. Getter methods (also called accessor methods) allow you to retrieve the value of a private data member, and setter methods (also called mutator methods) allow you to modify the value of a private data member. Here's how getters and setters are related to encapsulation:

1. **Getters (Accessor Methods)**:

   * Getter methods are public methods defined within a class to provide controlled access to private data members.
   * They are used to retrieve the values of private data members.
   * Getters typically have a `const` qualifier in their method signatures to indicate that they do not modify the object's internal state.

   ```cpp
   cppCopy codeclass MyClass {
   private:
       int myValue;

   public:
       int GetValue() const {
           return myValue;
       }
   };
   ```
2. **Setters (Mutator Methods)**:

   * Setter methods are public methods defined within a class to modify the values of private data members.
   * They are used to update the internal state of an object.
   * Setters can perform validation and enforce constraints on the values being set.

   ```cpp
   cppCopy codeclass MyClass {
   private:
       int myValue;

   public:
       void SetValue(int newValue) {
           if (newValue >= 0) {
               myValue = newValue;
           }
       }
   };
   ```

By using getter and setter methods, you can achieve several objectives related to encapsulation:

* **Controlled Access**: You can enforce controlled access to the private data members, allowing you to define rules for reading and modifying the data.
* **Data Validation**: Setters can include validation logic to ensure that the data remains in a valid state.
* **Abstraction**: Getter and setter methods abstract away the details of how the data is stored or manipulated, providing a clean interface to the class's users.
* **Flexibility**: If the internal representation of the data changes, you can update the getter and setter methods without affecting the external code that uses the class.
* **Encapsulation**: Together with private data members, getter and setter methods contribute to the encapsulation of data and behavior within a class.

Using getter and setter methods is a common practice in object-oriented programming and contributes to the principles of encapsulation and information hiding, allowing you to manage and protect the internal state of objects while providing controlled access to it.
