C++

What Are Getter Functions in C++?

In C++ Object-Oriented Programming, encapsulation is a technique to hide data by declaring it under the private attribute in a defined Class. The private data of members are not accessible from outside the class.

What Are Getter Functions in C++?

When the private data members in C++ during encapsulation need to be accessed for modification, the getter functions are called Getter functions and to fetch the private variables value in C++ the getter functions are used. The use of the getter function makes the code readability easy and allows the protection of data, making it available to the relevant members of the class only.

Example 1

This code illustrates the usage of the getter() function in C++:

#include <iostream>

using namespace std;

 

class Item {

  private:
   
    int price;

  public:
 
    Item(int p) {
      price = p;
    }

   
    int getPrice() {
      return price;
    }


};

 

int main() {

  Item wallet(20);

  cout << "The price of the wallet is $" << wallet.getPrice();

  return 0;

}

In this source code, an Item Class is defined, and the int price is declared as the private data member of it. The getPrice() function is used to retrieve the value of the price since being a private member cannot be accessed outside the class without using get() function. In the main function, the getPrice() function is called on the object to return the value.

The price of the wallet is obtained by using the get() function, which is printed as $20.

Example 2

This example illustrates the calculation of the area of the circle using the get() function in C++:

#include <iostream>

using namespace std;

class Circle {

 

private:

    float area;

    float radius;

 

public:

    void getRadius()

    {

        cout << "Enter the radius of Circle: ";

        cin >> radius;

    }

    void findArea()

    {

        area = 3.14 * radius * radius;

        cout << "Area of the circle = " << area;

    }

};

int main()

{

    Circle cir;

    cir.getRadius();

    cir.findArea();

}

In this source code, the Circle Class is defined, and the parameters of the circle are defined as private members. To find the area of this circle, these members are accessed using the get() function:

Conclusion

While dealing with sensitive data, the data encapsulation technique is used in C++. The members of the class that are declared under private attribute cannot be accessed outside the class and hence are secured When the private data members during encapsulation need to be accessed for modification, the getter functions are called. Getter functions in C++ are used to fetch the value of private variables for modifications.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.