info@tutsfinder.in



Abstraction


Abstraction is a process to hide the implementation details from the users and showing only the functionality. It displays only essential things.

Data abstraction is the most essential feature of Object Orientd programmin C++.

For example: Like ATM Machine, we can see only functionality but don’t know internal details that how it works.

Advantages:


• Increases reusability of code by minimizes code redundancy.

• Separates program into code and implementation.

• Increases code readability.

We can achieve abstraction by using these two ways in C++


By using Classes: In class we can group data members and member functions using access specefiers.A class can allow which data members will be visible the class and which is not.

By using Header files: One more type of abstraction in C++ can be header files. We can use many method which is already defined in header files of C++. For example – sqrt(), whenever we need to calculate the square root of any number, we just need to implement math.h class.



#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