Getters and Setters in C++

What are Getters and Setters?

Getters and setters in C++ are as the name suggests functions that are created to set values and to fetch i.e. get values. Here we would learn about these functions from its basics.

Getter and Setter

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

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.

Example Code –

#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;
    
    // shape.height or shape.width wont work as they are private

    return 0;
}

Output

The Height is : 5 
The Width is : 2

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription