C++ Access Specifiers
Access specifiers control the visibility of class members (variables and functions) and determine which parts of the program can access them. The common access specifiers in C++ are:
- Public: Members declared as public are accessible from anywhere, including outside the class, derived classes, and within the same class.
- Private: Members declared as private are only accessible within the same class. They cannot be accessed from outside the class or by derived classes.
- Protected: Members declared as protected are accessible within the same class and derived classes, but not from outside the class.
The following table explain these access specifiers
Access Specifier | Same Class | Derived Class | Outside Class |
---|---|---|---|
Public | YES | YES | YES |
Private | YES | NO | NO |
Protected | YES | YES | NO |
Important: In C++, both friend functions and friend classes allow access to private and protected members of a class.
A friend function is a special function in C++ that is not a member of a class but can access its private and protected members. This allows the friend function to operate on the class’s internal data without being a member of the class. |
C++ Access Specifiers Program
#include <iostream> using namespace std;class Base { public: int publicVar; // Accessible anywhere Base() { void show() { private: protected: class Derived : public Base { // Accessing protected variable from the base class // The following line would cause an error because privateVar is private in the base class int main() { // Accessing public member from outside the class // The following lines will give an error because privateVar is private in the Base class baseObj.show(); // Accesses private and protected variables inside the class derivedObj.showDerived(); // Accesses public and protected variables in derived class return 0; |
Output:
Accessing Public Variable from outside the class: 10
Public Variable: 10
Private Variable: 20
Protected Variable: 30
Public Variable from Base: 10
Protected Variable from Base: 30