
Understanding Access Modifiers in C++
What Are Access Modifiers?
In C++, access modifiers are keywords used to define the level of access that members of a class (variables and methods) can have. They are essential for ensuring encapsulation, which is a core concept of Object-Oriented Programming (OOP). By using access modifiers, we control how the internal data of a class is accessed, modified, and protected.
Access modifiers in C++ include:
private: Members are accessible only within the same class.protected: Members are accessible within the class and derived classes.public: Members are accessible from anywhere in the program.
By controlling access, access modifiers help:
- Protect the internal state of a class.
- Promote data encapsulation.
- Allow controlled access to data and functionality.
Types of Access Modifiers
private:- Definition: Members marked as
privateare accessible only within the same class. They are hidden from derived classes and external code. - Use Case: To protect internal data and ensure that class users can’t modify sensitive data directly.
- Definition: Members marked as
protected:- Definition: Members marked as
protectedare accessible within the same class and any derived (child) classes. However, they are not accessible by objects of the class. - Use Case: To allow derived classes to access and modify base class data, while still hiding the data from the outside world.
- Definition: Members marked as
public:- Definition: Members marked as
publicare accessible from anywhere. This includes external code, objects, and even derived classes. - Use Case: For functions and variables that need to be accessed or modified by external code.
- Definition: Members marked as
Code Example
class number {
private:
int privateVar; // Private variable, accessible only within this class.
protected:
int protectedVar; // Protected variable, accessible within the class and derived classes.
public:
int publicVar; // Public variable, accessible from anywhere.
// Constructor to initialize the variables
number() {
privateVar = 10;
protectedVar = 20;
publicVar = 30;
}
// Public function to display values of all members
void display() {
cout << "Private Variable: " << privateVar << endl;
cout << "Protected Variable: " << protectedVar << endl;
cout << "Public Variable: " << publicVar << endl;
}
};
Explanation of the Base Class
- Private Member (
privateVar):- The
privateVaris declaredprivate, meaning it can only be accessed inside thenumberclass. It is hidden from both derived classes and external code. - Purpose: Used to encapsulate and protect data that shouldn’t be directly modified by the outside world.
- The
- Protected Member (
protectedVar):- The
protectedVaris declaredprotected, meaning it can be accessed within thenumberclass and any class derived from it (like theDerivedclass). - Purpose: Useful for allowing derived classes to interact with base class members, while still hiding the data from external code.
- The
- Public Member (
publicVar):- The
publicVaris declaredpublic, meaning it is accessible from anywhere in the program, including objects of the class, and even in derived classes. - Purpose: Typically used for properties that need to be freely accessed or modified by external code.
- The
- Constructor:
- The constructor initializes all three variables with values (
privateVar = 10,protectedVar = 20,publicVar = 30).
- The constructor initializes all three variables with values (
- Function (
display):- The
display()function prints the values of the three variables to show how access modifiers impact the visibility of the class members.
- The
Derived Class Code (Derived class)
class Derived : public number {
public:
// Accessing protected variable in the derived class
void displayProtected() {
cout << "Protected Variable (from Derived class): " << protectedVar << endl;
}
};
Explanation of the Derived Class
- Inheriting from
number:- The
Derivedclass inherits from thenumberclass using public inheritance. This means all public and protected members of thenumberclass are inherited byDerived.
- The
- Accessing Protected Member:
- The
displayProtected()function in theDerivedclass prints the value ofprotectedVar. This is allowed becauseprotectedVaris protected and can be accessed by derived classes.
- The
- Private Members Not Inherited:
privateVaris a private member of thenumberclass and cannot be accessed directly by theDerivedclass. This demonstrates the limited access of private members.
Main Function Code
int main() {
// Object of base class
number obj;
// Accessing public variable directly
cout << "Public Variable: " << obj.publicVar << endl;
// Displaying all variables using the public function
obj.display();
// Object of derived class
Derived derivedObj;
// Accessing protected variable via derived class
derivedObj.displayProtected();
return 0;
}
Explanation of the Main Function
- Creating
obj(Object ofnumber):objis an instance of thenumberclass. Using this object, we can access the public memberpublicVardirectly.
- Calling
display():- The
obj.display()function is called, which prints the values of all three variables (private, protected, and public). AlthoughprivateVaris private, it can still be accessed within the class through a public function.
- The
- Creating
derivedObj(Object ofDerived):derivedObjis an instance of theDerivedclass. SinceDerivedinherits fromnumber, it can access the protected memberprotectedVarthrough thedisplayProtected()function.
Output of the Code
Public Variable: 30
Private Variable: 10
Protected Variable: 20
Public Variable: 30
Protected Variable (from Derived class): 20
Explanation of the Output
Public Variable: 30:- This value is accessed directly from the
objobject since it is a public member.
- This value is accessed directly from the
Private Variable: 10:- This value is printed by the
display()function. Although it is private, it can be accessed within the class.
- This value is printed by the
Protected Variable: 20:- This value is printed by the
display()function.protectedVaris accessible within thenumberclass.
- This value is printed by the
Protected Variable (from Derived class): 20:- This value is printed by the
displayProtected()function in theDerivedclass. The derived class can access protected members of the base class.
- This value is printed by the
Access Summary Table
| Access Modifier | Access Inside Class | Access in Derived Class | Access via Object |
|---|---|---|---|
private | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ❌ |
public | ✅ | ✅ | ✅ |
Conclusion
In this tutorial, we explored the three main access modifiers in C++:
private: Restricts access to within the class.protected: Allows access within the class and derived classes, but not by external code.public: Grants access to members from anywhere in the program.
By using these access modifiers, we can control data visibility, ensuring that class members are accessible in a controlled and secure manner. Access modifiers are fundamental in achieving encapsulation and data hiding, which are essential principles of object-oriented programming.
One thought on “Understanding Access Modifiers in C++”
worry in CBD wellness but don’t know where to lead off? register our comprehensive https://www.cornbreadhemp.com/collections/thc-gummies manoeuver to discover how unadulterated CBD, wax spectrum CBD, and CBD isolate patronise your physical structure. dissimilar THC, pure CBD cater non-psychoactive benefits that sustenance you sharp and make relaxed. Whether you opt CBD vegetable oil drops, CBD pabulum, or CBD abridgement, we excuse CBD dosage so you rump plunk the best CBD product. lead off your instinctive CBD journey nowadays with sodding authority in certified organic fertilizer CBD!