ABSTRACTION


                     PREVIOUS                                                                                                          NEXT

In C++ we use access labels to define the abstract interface to the class. A class may contain zero or more access labels:-

  • Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members.
  • Members defined with a private label are not accessible to code that uses the class. The private sections hides the implementation from code that uses the type.

There are no restrictions on how often an access label may appear. Each access label specifies the access level of the succeeding member definitions. The specified access level remains in effect until the next access label is encountered or the closing right brace of the class body is seen.Benefits of Data Abstraction:-

  • Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.
  • The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data are public, then any function that directly accesses the data members of the old representation might be broken.

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

#include < iostream.h > 
using namespace std; 
class Adder 
{
   public: 
      Adder(int i = 0)  	 // constructor 
      {
        total = i; 
      } 
      void addNum(int number) 	 // interface to outside world 
      { 
          total += number; 
      } 
      int getTotal() 		 // interface to outside world
      {
          return total; 
      }; 
   private:  			 // hidden data from outside world 
      int total; 
};
int main( ) 
{ 
   Adder a; 
   a.addNum(10); 
   a.addNum(20); 
   a.addNum(30); 
   cout << "Total " << a.getTotal() << endl; 
   return 0; 
} 

When the above code is compiled and executed, it produces following result:
Total 60
Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that the user doesn't need to know about, but is needed for the class to operate properly.







Powered by Blog - Widget
Face Upward - Widget