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() {
publicVar = 10;
privateVar = 20;
protectedVar = 30;
}

void show() {
cout << “Public Variable: ” << publicVar << endl;
cout << “Private Variable: ” << privateVar << endl;
cout << “Protected Variable: ” << protectedVar << endl;
}

private:
int privateVar; // Accessible only within the class

protected:
int protectedVar; // Accessible within the class and derived classes
};

class Derived : public Base {
public:
void showDerived() {
// Accessing public variable from the base class
cout << “Public Variable from Base: ” << publicVar << endl;

// Accessing protected variable from the base class
cout << “Protected Variable from Base: ” << protectedVar << endl;

// The following line would cause an error because privateVar is private in the base class
// cout << “Private Variable from Base: ” << privateVar << endl; // Error
}
};

int main() {
Base baseObj;
Derived derivedObj;

// Accessing public member from outside the class
cout << “Accessing Public Variable from outside the class: ” << baseObj.publicVar << endl;

// The following lines will give an error because privateVar is private in the Base class
// cout << baseObj.privateVar << endl; // Error
// cout << baseObj.protectedVar << endl; // Error

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