What are getter functions in C++?

Encapsulation is one of the fundamental concepts of the Object-oriented programming paradigm. It is the process of wrapping the data stored in a private member variable inside its getter and setter methods. The getter function is used to retrieve the variable value and the setter function is used to set the variable value.

Remember: You can directly access public member variables, but private member variables are not accessible. Therefore, we need getter functions.

svg viewer

Code

In the code below, we have an Item class with the private member variable price. Since you cannot directly access this variable outside this class, the public member function i.e., getPrice() is used.

Try changing line 2323 to bag.price instead of bag.getPrice(). You will see ​an error.

#include <iostream>
using namespace std;
class Item {
private:
// Private member variable
int price;
public:
// constructor
Item(int p) {
price = p;
}
// getter function
int getPrice() {
return price;
}
};
int main() {
Item bag(20);
cout << "$" << bag.getPrice();
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved