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.
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 to
bag.price
instead ofbag.getPrice()
. You will see an error.
#include <iostream>using namespace std;class Item {private:// Private member variableint price;public:// constructorItem(int p) {price = p;}// getter functionint getPrice() {return price;}};int main() {Item bag(20);cout << "$" << bag.getPrice();return 0;}
Free Resources