TExcelTAD
Home › C++ › C++ Access Specifiers

C++ Access Specifiers

Access specifiers control who may use the members of a class. They are the language feature behind encapsulation: you decide which parts of a class form its public interface and which parts are internal details.

The three specifiers

Specifier Accessible from
public anywhere — any code that has the object
private only member functions (and friends) of the same class
protected the class itself and classes derived from it

An access specifier applies to every member below it until the next specifier:

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

class Thermostat {
public:
    void setTarget(double celsius) {
        if (celsius >= 5 && celsius <= 30) {
            target = celsius;
        } else {
            cout << "Rejected " << celsius << " (allowed 5-30)\n";
        }
    }
    double getTarget() const { return target; }

private:
    double target = 20;
};

int main() {
    Thermostat t;
    t.setTarget(23.5);
    t.setTarget(80);
    cout << "Target: " << t.getTarget() << "\n";
    // t.target = 80;   // error: 'double Thermostat::target' is private
}
Rejected 80 (allowed 5-30)
Target: 23.5

Because target is private, the only way to change it is through setTarget, which enforces the allowed range. No code anywhere can put the thermostat into an invalid state.

What the compiler says

Trying to touch a private member from outside is a compile-time error, not a runtime one:

cpp
class Vault {
private:
    int pin = 4321;
};

int main() {
    Vault v;
    v.pin = 0;     // error: 'int Vault::pin' is private within this context
}

protected and inheritance

protected members are hidden from the outside world, but derived classes can use them. Here Sensor keeps its raw reading protected so that subclasses can build on it:

cpp · try it yourself
#include <iostream>
using namespace std;

class Sensor {
public:
    void update(double value) { raw = value; }
protected:
    double raw = 0;     // visible to derived classes
private:
    int serial = 1001;  // visible only inside Sensor
};

class FahrenheitSensor : public Sensor {
public:
    double fahrenheit() const {
        return raw * 9 / 5 + 32;   // OK: raw is protected
        // serial is NOT accessible here
    }
};

int main() {
    FahrenheitSensor s;
    s.update(25);
    cout << s.fahrenheit() << "\n";
    // cout << s.raw;   // error: protected outside the class hierarchy
}
77

Private means "private to the class", not "to the object"

Access is checked per class. A member function may access the private members of another object of the same class — handy for comparisons and copying:

cpp · try it yourself
#include <iostream>
using namespace std;

class Money {
public:
    explicit Money(long cents) : cents(cents) {}
    bool isMoreThan(const Money& other) const {
        return cents > other.cents;     // other's private member: allowed
    }
    Money plus(const Money& other) const {
        return Money(cents + other.cents);
    }
    void print() const {
        cout << cents / 100 << "." << (cents % 100 < 10 ? "0" : "") << cents % 100 << "\n";
    }
private:
    long cents;
};

int main() {
    Money a(1250), b(399);
    cout << boolalpha << a.isMoreThan(b) << "\n";
    a.plus(b).print();
}
true
16.49

Conventions

  • Put the public section first — it is what users of the class read.
  • Make data members private by default; expose behaviour through public methods.
  • Use protected sparingly. Protected data creates a tight coupling between base and derived classes.

Tip: Many style guides add a suffix or prefix to private members, such as balance_ or m_balance, so they are easy to tell apart from parameters and locals.

Test yourself

Which members can a derived class access in its base class?

  1. Only public
  2. public and protected
  3. public, protected and private
  4. None

When is an access violation such as obj.secret = 1; detected?

  1. At runtime
  2. At compile time
  3. Only in debug builds
  4. Never

Can a method of class Money read the private members of another Money object?

  1. Yes, access is per class
  2. No, only its own object
  3. Only if it is static
  4. Only with a cast