Pages

Sunday, June 7, 2015

Example of Data Abstraction

Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example:

#include <iostream>
#include<conio.h>
using namespace std;

class Add{
   public:
      // constructor
      Add(int i = 0)
      {
        total = i;
      }
      // interface to outside world
      void addNum(int number)
      {
          total += number;
      }
      // interface to outside world
      int getTotal()
      {
          return total;
      };
   private:
      // hidden data from outside world
      int total;
};
int main( )
{
   Add a;
  
   a.addNum(10);
   a.addNum(20);
   a.addNum(30);

   cout << "Total " << a.getTotal() <<endl;
   return 0;
}

No comments:

Post a Comment