info@tutsfinder.in



Encapsulation


It is mechanism to encapsulate or wrap up all the data members and member functions into a single entity that is class .It is used to prevent data from directly access. It is on eof the important feature of ObjectOriented that is helps in to data hiding.

Encapsulation can be achieved in two ways:

1. By using setter and getter methods.

2. Making all variables as private.



class Car {
   public:
      double printInfo(void) {
       cout << ”Brand is BMW”;
	cout << ”Model is X5”;
      }

   private:
      int price;      
};


The variable price is set to private. This means that this can be accessed only by other members of the Car class, and not by any other part of your program. This is one way to achieve encapsulation in C++.



#include <iostream>
using namespace std;
class Exp
{
    private:
    int x;
    public:
    Exp(int a)
    {
        x =a;
    }
    int display()
    {
        return x;
    }
};
int main()
{
    Exp a(8);
    cout << "Number is: " << a.display();
    return 0;
}


Output:

Number is: 8


In the above program, we show how encapsulation works. We have a private member x which cannot be accessed from the main function. The only way to access it is by creating a object of class Exp.



#include <iostream>
using namespace std;

class Multiplication {
   
      // constructor
      public:
      Multiplication(int i=1) {
         Ans = i;
      }
      
      void mul(int num) {
         Ans *= num;
      }
      
      int getMult() {
         return Ans;
      };
      
   private:
      // hidden data from outside world
      int Ans;
};

int main() {
   Multiplication obj;
   
   obj.mul(5);
   obj.mul(2);
   obj.mul(3);

   cout << "Ans is : " << obj.getMult() << endl;
   return 0;
}


Output:

Ans is : 30