Abstraction and Encapsulation

Encapsulation:

Encapsulation is a process of combining data members and functions in a single unit called class. This is to prevent the access to the data directly. To get access to the data member functions of the class are used. It helps in data hiding. It is one of the popular features of object oriented programming.
 

How to achieve Encapsulation in a class:

  • For this purpose you have to make all the data members private.
  • Then create public getter and setter methods in such a way that the way function set the value of the data member and the hat function get the value of the data member.

Abstraction:

  Abstraction is similar to the concept of a black box. Input goes in, black box does something and output comes out. It doesn't matter what happens in the black box, all you have to know is that it works. 
 It means displaying only essential information and hiding the background details or implementation.

Real world example of abstraction:
    
 A real life example of Abstraction is ATM Machine. We only know the methods   like cash withdrawal, money transfer, retrieve etc. This technique is called abstraction. But we don't know internal details about ATM that are encapsulated. 

How to achieve Abstraction:

  • Make objects of your class
  • Must know what methods and data members it can access and use them.

Example of encapsulation and abstraction:

#include <iostream>
using namespace std;

// combining data members and functions in a single unit called class, named Encap.

// Encapsulation starts
   class Encap{

  private:

       int age,string name;
       public:
       void
setDat(int a,string b){
           age=a;
           name=b;
       }
       int getAge(){
           return age;
}
       string getName(){
           return name;
       }
   };

//Encapsulation ends

int main() {

// Abstraction 
     Encap person1;
     Encap person2;
     person1.setDat(15,"Kabir");
     person2.setDat(18,"Khalid");
     cout<<"Person 1:"<<endl;
     cout<<person1.getAge()<<endl;
     cout<<person1.getName()<<endl;
     cout<<"Person 2:"<<endl;
     cout<<person2.getAge()<<endl;
     cout<<person2.getName()<<endl;
    return 0;
}

Output:

Person 1:

15

Kabir

Person 2:

18

Khalid


You can have a quick editorial here:



Comments

  1. Wow this is what I was looking for. Very nice explaination and also the video. ����

    ReplyDelete
  2. thank you so much for providing us a amazing information

    ReplyDelete
  3. Thanks a lot... It helps me alot❤️❣️

    ReplyDelete

Post a Comment

Popular posts from this blog

Virtual function in c++

HK Lite's Portfolio

Multiple, Multilevel, Hybrid and Hierarchical inheritance