Encapsulation

All  c++  programs  are  composed  of  the  following  two  fundamental   elements

  • Program  statements(code)-This  is  the  part  of a  program  that  performs  actions  and  they  are  called  functions
  • Program  data-The  data  is  the  information  of  the program  which  gets  affected  by the  program functions

Encapsulation  is  an Object Oriented  Programming  concept  that  binds  together  the  data and  functions  that  manipulate  the  data,and keeps  both  safe  from   outside  interference  and  misuse,Data encapsulation  led  to  the important  OOP  concept  of  data  hiding

Data  encapsulation is  a  mechanism  of  bundling  the  data,and  the functions  that  use  them  and  data  abstraction  is  a  mechanism  of  exposing  only  the  interfaces  and hiding  the implementation  details from  the  user.

C++ supports  the  properties  of  encapsulation  and  data hiding  through  the  creation of  user-defined  types,called  classes.The  class contain private ,protected  and  public  members.By  default  all items  defined  in a  class  are  private

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

eg:

#include<iostream.h>

class  Adder {

   public:
   
      Adder(int i=0) {

         total = i;

        }

      void  addNum(int number)  {
       
         total+=number;
   
        }

       int getTotal()  {
    
         return total;

        };
   
    private:

          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  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  them  to use the class 
  • The private member total is something  that  is hidden  from  the outside world
  • but is needed  for class to operate properly

Posted on by