C++ Programming
Data Abstraction and Encapsulation
What is Data Abstraction ?
What is Data Abstraction ?
At first, we don’t know how addNum is implemented in Adder class.
But we only know that this function will only add numbers.
Benefits of Data Abstraction
Access Modifiers Enforces Abstraction
What is Encapsulation ?
What is Encapsulation ?
Data such as length, breadth, and height were
set as private.
This way, other classes cannot access these
values, only the class itself can directly use it.
This method is called data hiding/ data
encapsulation
Class Access Modifiers
Access control of inherit classes
Access Specifier in UML
+ = public
- = private
# = protected
Access Specifier in UML
+ = public
- = private
# = protected
Access Specifier in UML
+ = public
- = private
# = protected
Public Access Specifier
• Public access specifier allows a class to expose its member
variables and member functions to other functions and
objects.
“Any public member can be accessed from outside the class.”
Public Access Specifier - Example
“Any public member can be accessed from outside the class.”
• Parent Class:
✔ All of its members
• External Class:
✔ parent_var2
✔ parent_function2
• Child Class:
✔ parent_var2
✔ parent_function2
Example
RESULT
:
Private Access Specifier:
• Private access specifier allows a class to hide its member
variables and member functions from other functions and
objects.
“Only functions of the same class can access its private
members.”
Private Access Specifier
Private Access Specifier - Example
“Only functions of the same class can access its private members.”
• Parent Class:
✔ All of its members
• External Class:
x None
• Child Class:
x None
Example
Box.h Box.cpp
Example
Main.cpp
Protected Access Specifier:
• Protected access specifier allows a child class to access the member
variables and member functions of its base class. This way it helps in
implementing inheritance.
Protected Access Specifier: - Example
“Allows a child class to access the member variables and member
functions of its base class”
• Parent Class:
✔ All of its members
• External Class:
x None
• Child Class:
✔ parent_var2
✔ parent_var3
✔ parent_function2
✔ parent_function3
Example
Following example is similar to above example and
here width member will be accessible by any
member function of its derived class SmallBox.
Resul
t:
Important Points
• Data members should be set as private. This is applicable if the data
members may hold important information.
• Function members can be set as public since they are used by other
classes or program. But there are instance that you might need to set
function members as private that can be used only inside the class.
For example, calculation of income, etc.
• Use setter/getter functions for setting the data members and getting
the value of data members as well.