adsense


Thursday, 26 November 2015

C++ LANGUAGE DATA ENCAPSULATION

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE DATA ENCAPSULATION





DATA ENCAPSULATION 


defined after the public specifier are accessible 
by all other functions in your program. 
Making one class a friend of another, exposes the implementation 
details and reduces encapsulation. The ideal is to keep as many of 
the details of each class hidden from all other classes as possible. 

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

#include <iostream> 
using namespace std; 
 
class Adder{ 
   public: 
      // constructor 
      Adder(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( ) 
{ 
   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 
the 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 is 
hidden from the outside world, but is needed for the class 
to operate properly.


No comments: