Open In App

How to Write Getter and Setter Methods in C++?

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to show how to Create a Class with Getter and
// Setter Methods
#include <iostream>
using namespace std;
class GFG {
private:
    int length;
    int width;
  
public:
    // Constructor
    GFG(int len, int wid)
    {
        length = len;
        width = wid;
    }
  
    // Getter methods
    int getLength() const { return length; }
    int getWidth() const { return width; }
  
    // Setter methods
    void setLength(int len) { length = len; }
    void setWidth(int wid) { width = wid; }
};
  
// Driver Code
int main()
{
    // Create an object of Rectangle class
    GFG rect(5, 3);
    cout << "Length: " << rect.getLength() << endl;
    cout << "Width: " << rect.getWidth() << endl;
    // Use setter methods to modify member variables
    rect.setLength(7);
    rect.setWidth(4);
    // Display updated values
    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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads