![]() |
In C++, getters and setters are part of data encapsulation used to protect our data, particularly when creating classes. These are public methods that are used to access and modify the private or protected members of a class. In this article, we will learn how to use getters and setters in C++. Getters in C++In C++, getters, also known as accessors (as they access the value), are the public member functions that are used to fetch private member’s values. In general, the getter starts with the word “get” followed by the variable name. Syntax to Define GetterdataType getVariableName() const { Setters in C++Setters, also known as mutators (as they update the value), are also the public member functions that set the value of a private member variable. In general, the setter starts with the word “set” followed by the variable name. Syntax to Define Settervoid setVariableName(dataType newValue) { C++ Program to Demonstrate the Use of Getter and Setter.The below example demonstrates how we can use getters and setters in C++.
Output Salary is: 10000 Explanation: In the above program, we have accessed the private member “salary” of class employee using the setter setSalary() method and getter getSalary() method. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |