Encapsulation & Accessibility in C++

Encapsulation : 

Encapsulation is another major component of OOP . the process of restricting access to data is called encapsulation. Encapsulation can be used to hide data members and members' functions. 

note: Class members are actually Class variables(data) and functions 

Access modifiers: 

Access modifiers are keywords in OOP that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate encapsulation. in C++ there are 3 access modifiers 
  1. public 
  2. protected
  3. private 

Explanation:

Suppose you have created a class A. 
Then The private, public and protected members of class A can be accessed within the class. Now say you have created an object of this class then the object can only access the public members of the class. 

Similarly, if you derive a class B from the base class A then the derived class B can access the protected & public members of the base class A

now if you create an object of type Class B then the object can only access the public members of class B. now whether this object can access the members of the Base class A depends on the inheritance type. if it's public then this object of type class B can access public members of class A . on the other hand if the inheritance type is private then this object of type class B won't be able to access public members of class A.   

Now see the following diagram and you will understand everything 

Access specifiers without inheritance: 

Access specifiers with an inheritance: 










0 comments:

Post a Comment

Categories

Pages

Firmware Engineer

My photo
Works on Firmware, Embedded Linux, Smart Metering, RTOS, IoT backend

Contact Form

Name

Email *

Message *

Copyrighted by Hassin. Powered by Blogger.