21CSC101T: Abstraction and Encapsulation
21CSC101T: Abstraction and Encapsulation
Abstraction and
Encapsulation
Abstraction
• Abstraction is the process of providing only the essential details to the outside
world and hiding the internal details
• That is, representing only the essential details and hiding the implementation
details
#include <iostream>
using namespace std;
class sample {
public: If you execute the above program, the private
int a, b; member function will not be accessible and
public: hence the following error message will appear
void get_val() like this in compiler:
{
cout<< "Enter Two values : ";
cin>>a>>b;
}
private:
void display()
{ cout << a << " " << b;
cout << endl;
}
};
int main()
{
sample s;
s.get_val();
s.display();
}
Abstraction is an Object-Oriented Programming
(OOP) concept that hides implementation details
and only shows essential features to the user. In
C++, we achieve abstraction using classes and
access modifiers (private, public).
Abstraction
Only necessary functions (setDetails(), displayDetails())
are exposed.
Private data (rollNo, name, marks) is hidden from direct
access.
class implementAbstraction
int main()
{
private: {
int a, b; implementAbstraction obj;
obj.set(10, 20);
public:
// method to set values of obj.display();
// private members return 0;
void set(int x, int y) }
{
a = x;
b = y;
} Output:
a = 10
void display()
{ b = 20
cout<<"a = " <<a << endl;
cout<<"b = " << b << endl;
}
};
Data Hiding → Private members : a, b cannot be accessed directly. That
is hidden from direct access.
Application of Abstraction
• For example, when you send an email to someone you just click send and
you get the success message, what actually happens when you click send,
how data is transmitted over network to the recipient is hidden from you
ENCAPSULATION
• DATA ENCAPSULATION
– Encapsulation is defined as wrapping up of data and information under a
single unit.
– In OOP, Encapsulation is defined as binding together the data and the
functions that manipulates them.
– Combining data and functions into a single unit called class and the process is
known as Encapsulation.
Encapsulation also helps us to make a flexible code which is easy to change and
maintain.
Example
Note: A private member function cannot be accessed outside the class. So it cannot be
accessed inside the main function