C++ Access Specifiers

The gatekeepers of your code. Master public, private, and protected.

Curated by

The Three Levels of Access

Think of a class like a building. Different areas have different rules about who can enter.

Public Park
Real Life Analogy: Public Park
public

Public

Accessible from anywhere. Like a park, anyone can walk in.

  • check Inside the class
  • check In derived classes
  • check External functions (main)
Bank Vault
Real Life Analogy: Bank Vault
lock

Private

Accessible ONLY within the class. Strictly confidential.

  • check Inside the class
  • close In derived classes
  • close External functions (main)
Family Home
Analogy: Family Inheritance
shield_person

Protected

Accessible in the class AND by children (derived classes).

  • check Inside the class
  • check In derived classes
  • close External functions (main)

dvr Interactive Code Compiler

See how the compiler reacts in real-time. Change the access specifier of the goldBars variable inside the BankVault class and observe if main() can access it.

Configuration

info What's happening?

The variable is public. This means anyone, including the external main() function, can directly read and write to it. It's like leaving the vault door wide open.

main.cpp
class BankVault {
public::
    int goldBars = 100;
};

int main() {
    BankVault myVault;
    
    // Trying to access from outside
    
myVault.goldBars = 50;
return 0; }
check_circle Build Successful: 'goldBars' is accessible.

account_tree Inheritance & Access

When a class inherits from another class, the access levels can change based on the type of inheritance.

Base Class public: int x; protected: int y; private: int z;
public inheritance
Derived Class public: int x; protected: int y; z: inaccessible
Public Inheritance: "Is-a" relationship. Public members stay public, protected stay protected.

Test Your Knowledge

1. Which specifier allows members to be accessed by derived classes but NOT by the outside world?

2. In 'class Car : private Vehicle', how do public members of Vehicle appear inside Car?