C++ OOP - Data Abstraction and Encapsulation
C++ OOP - Data Abstraction and Encapsulation
+ = 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
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.