Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
functions
getter
oop

What are getter functions in C++?

Educative Answers Team

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;
}

RELATED TAGS

c++
functions
getter
oop
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring