How to Write Getter and Setter Methods in C++?
Last Updated :
27 Feb, 2024
In C++, classes provide a way to define custom data types that can encapsulate data and methods related to that data. Getter and setter methods are commonly used to access and modify private member variables of the class allowing for the controlled access and modification of data. In this article, we will learn how to create a class with getter and setter methods in C++.
Getter and Setter Methods for a Class in C++
To create a class with getter and setter methods in C++, we define the class with private data members and public methods to get (read) and set (write) these data members.
Example:
Consider a class Student
with private data member age
, and public getter and setter methods for these data members.
// Getter methods
DataType getAge() const {
return age;
}
// Setter methods
void setAge(DataType newValue) {
age = newValue;
}
C++ Program to Create a Class with Getter and Setter Methods
C++
#include <iostream>
using namespace std;
class GFG {
private :
int length;
int width;
public :
GFG( int len, int wid)
{
length = len;
width = wid;
}
int getLength() const { return length; }
int getWidth() const { return width; }
void setLength( int len) { length = len; }
void setWidth( int wid) { width = wid; }
};
int main()
{
GFG rect(5, 3);
cout << "Length: " << rect.getLength() << endl;
cout << "Width: " << rect.getWidth() << endl;
rect.setLength(7);
rect.setWidth(4);
cout << "Updated Length: " << rect.getLength() << endl;
cout << "Updated Width: " << rect.getWidth() << endl;
return 0;
}
|
Output
Length: 5
Width: 3
Updated Length: 7
Updated Width: 4
Share your thoughts in the comments
Please Login to comment...