Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Accessor and Mutator Methods | Encapsulation Overview
C++ OOP
course content

Зміст курсу

C++ OOP

C++ OOP

1. Fundamentals of OOP
2. Constructors and Destructors
3. Encapsulation Overview
4. Inheritance Overview
5. Polymorphism Overview

bookAccessor 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.

cpp

main

copy
12345678910111213141516
#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.

What alternative name is commonly used for mutator methods in programming?

What alternative name is commonly used for mutator methods in programming?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4
some-alt