Access Modifiers

What Are the Three Types of Access Specifiers?

C++ has three access specifiers: public, private and protected. Learn what each one allows, who can reach each member, and which one to use.

On this page
  1. public
  2. private
  3. protected
  4. Who can reach each one
  5. A Vehicle example
  6. Which one to use

C++ has three access specifiers: public, private and protected. Each one decides which code can use the members listed under it. public members are open to any code that can see the class, private members are limited to the class and its friends, and protected members also reach derived classes. C++ uses the term access specifier, while many other languages say access modifier for the same idea.

public

public members form the interface of the class, the functions other code is meant to call. Any code that can see the class can use them.

private

private members hold internal state. Only the class’s own member functions and its friends can use them. Changing them through member functions lets the class keep its data valid.

protected

protected members are for base classes that want derived classes to reach some internal data while keeping it away from ordinary outside code. The class itself, its friends and derived classes can use them. Other code cannot.

Who can reach each one

Specifier Same class Derived class Friend Other code
public Yes Yes Yes Yes
protected Yes Yes Yes No
private Yes No Yes No

A Vehicle example

#include <iostream>

class Vehicle {
public:
    void start() { std::cout << "Starting\n"; }

protected:
    int wheels = 4;

private:
    int serialNumber = 12345;
};

class Motorcycle : public Vehicle {
public:
    Motorcycle() { wheels = 2; }   // OK: wheels is protected in the base class
};

int main() {
    Motorcycle m;
    m.start();                     // OK: public
    // m.wheels = 3;               // error: wheels is protected
    // int s = m.serialNumber;     // error: serialNumber is private
}

Which one to use

  • Make data members private by default, and expose what callers need through public functions.
  • Use public for the functions that form the class’s interface.
  • Use protected only when you design a base class that derived classes are meant to extend.

Access Modifiers in C++ puts all three into context, with the defaults and friends. Encapsulation in C++ explains why private data is worth the extra functions, and Friend Functions in C++ covers how a friend can still reach private members.

The complete guide to access modifiers

Access Modifiers in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

std::list in C++

std::list is the C++ standard library's doubly linked list. Learn to create one, add and remove elements, loop through it, and when to pick it over a vector.

std::list 5 min read