getters and setters in C++

What are Getters and Setters

Getters and setters are as the name suggests functions that are created to set values and to fetch i.e. get values. These vastly work with classes a lot and are famous ways of doing the same in the coding paradigm. We have some advantage of doing so –

  1. Data Protection – Using access modifiers and encapsulation we can set access rights throughout the code, thus direct access like object.data is discouraged.
  2. Code Readability – Getters and setters highly increase code readability as the coder only needs to look for specific get and set functions.
  3. Encourages code reuse – Imagine setting or fetching data that includes some manipulation like setting data but increasing the counter value by 1 every time the value is changed. Now, what if we want to change counter value by 10 everytime. Instead of writing or editing multiple lines wherever, object.data is used. You only need to do manipulation in the getter and setter function once.
Getters and Setters in C++

How it works?

Getters

Getters fetch value so they simply work as –

//getters
int getHeight()
{
return height;
}

int getWidth()
{
return width;
}

Setters

//setters
void setHeight(int h)
{
height = h;
}

void setWidth(int w)
{
width = w;
}

Let’s look at an example to understand how it works completely when objects and data protection is involved.

#include <iostream>
using namespace std;

class Shape
{
// as private so object.height and object.width is inaccessible
int height, width;
public:

//setters
void setHeight(int h)
{
height = h;
}

void setWidth(int w)
{
width = w;
}

//getters
int getHeight()
{
return height;
}

int getWidth()
{
return width;
}
};

int main()
{
Shape shape;
// setters
shape.setHeight(5);
shape.setWidth(2);

// getters
cout<<"The Height is : " << shape.getHeight() << endl;
cout<<"The Width is : " << shape.getWidth() << endl;
return 0;
}

Output – 

The Height is : 5 
The Width is : 2