C++

Example Of C++ Encapsulation – Detailed Instructions

Combining data elements and functions into a single class is the process of encapsulation. This is done to restrict direct access to the data; instead, the functions of the class are used to gain access to them. Data concealing is made easier by one of the widely used features of object-oriented programming (OOPs).

How a class implements encapsulation

1) Make all data members private to do this.
2) For every data member, create public setter and getter functions, with the set function setting the value and the get function retrieving the value.

Let’s examine this in a program example:

C++ Encapsulation Example

Here, the two data members num and ch have been designated as private, making them inaccessible to users outside of the class and enabling us to conceal the data. These data members’ values can only be obtained and changed using the public getter and setter functions.

#include<iostream>
using namespace std;
class ExampleEncap{
private:
   /* Since we have marked these data members private,
    * any entity outside this class cannot access these
    * data members directly, they have to use getter and
    * setter functions.
    */
   int num;
   char ch;
public:
   /* Getter functions to get the value of data members.
    * Since these functions are public, they can be accessed
    * outside the class, thus provide the access to data members
    * through them
    */
   int getNum() const {
      return num;
   }
   char getCh() const {
      return ch;
   }
   /* Setter functions, they are called for assigning the values
    * to the private data members.
    */
   void setNum(int num) {
      this->num = num;
   }
   void setCh(char ch) {
      this->ch = ch;
   }
};
int main(){
   ExampleEncap obj;
   obj.setNum(100);
   obj.setCh('A');
   cout<<obj.getNum()<<endl;
   cout<<obj.getCh()<<endl;
   return 0;
}

Output:

100
A

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button