Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 171 ยท Object-Oriented Programming

Access Specifiers and Encapsulation

Learn C++ access specifiers - public, private and protected, getters and setters done right, class invariants, leaking internals by reference, and designing clean class interfaces.

A class has two audiences. The implementation (the class's own member functions) needs full access to every piece of data. The users of the class (every other function in the program) should only see a carefully chosen set of operations. Access specifiers draw that line: public members are the interface, private members are the implementation, and the compiler enforces the boundary.

Hiding data is not about secrecy. It gives a class the power to guarantee its own correctness: if only the class's member functions can change its data, then a handful of functions decide whether the object stays valid, and you can reason about them in isolation. This lesson covers the three access levels, how access really works (it's per class, not per object), when getters and setters help and when they're noise, how to define and protect class invariants, and how to design interfaces that are easy to use correctly and hard to misuse. You'll build on Classes and Objects and Constructors and Member Initializer Lists.

public, private and protected

Specifier Accessible from
public Anywhere
protected The class's own members, its friends, and members of classes derived from it
private Only the class's own members and its friends

An access specifier applies to every member that follows it, until the next specifier. You can use each one as often as you like, in any order. Members of a class are private until the first specifier; members of a struct are public. Most style guides put the public section first, because that's what readers of the class care about, and the private details last.

C++ private data, public operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every path that changes target_ goes through set_target, so the thermostat can never hold an out-of-range value: not after construction, not after raise(), not after any sequence of calls. Uncomment the last line and the compiler stops it at build time.

Access is per class, not per object

A common surprise: a member function can access the private members of any object of the same class, not just the object it was called on. Access control is checked against code (is this function a member of the class?), not against objects. That's what makes comparison operators, copy constructors and operations combining two objects easy to write.

C++ Members can see other objects' private data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This is safe because the code doing the access is the class's own code, written by the same author who maintains the invariants. Outside code still can't touch cents_.

Class invariants

An invariant is a condition that is true for every object of a class whenever outside code can look at it. Examples: a Fraction is always in lowest terms with a positive denominator; a Date is always a real calendar date; a SortedList is always sorted; a Thermostat target is always between 5 and 30.

The contract is:

  1. Every constructor establishes the invariant (or throws).
  2. Every public member function preserves it: it may break it temporarily while it works, but restores it before returning.
  3. Private data means no one else can break it.

The payoff is enormous. Code that uses a SortedList never needs to re-check that it's sorted, and a bug that breaks sorting must be in one of a few member functions.

C++ A class that keeps its data sorted

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

best() and contains() are fast because of the invariant: the last element is the maximum, and binary search works only on sorted data. If scores_ were public, any code could push_back an unsorted value and silently break both.

Don't leak your internals

Making data private achieves nothing if a public member function hands out a non-const reference or pointer to it. Callers can then modify the private data directly, and the invariant is gone.

C++
class SortedScores {
public:
    std::vector<int>& data() { return scores_; }   // BAD: callers can push_back anything
    // ...
};

s.data().push_back(-5);        // compiles, and the list is no longer sorted

Safe ways to give read access:

  • Return by value for small data (int best() const).
  • Return a const& for large data you want to expose without copying: const std::vector<int>& data() const.
  • Return a read-only view: std::span<const int> or std::string_view. A view hides the container type, so you can switch to std::array or std::deque later without changing callers.

Remember that a returned reference or view is only valid as long as the object (and its buffer) is; storing it and then modifying the object can leave it dangling (Undefined Behavior and Memory Safety).

Getters and setters

A getter (accessor) returns a member's value; a setter (mutator) changes it. C++ has no special property syntax; they're ordinary member functions. Common naming styles are name() / set_name() (used by the standard library style and this course) and getName() / setName().

Getters and setters are useful when they do something: a setter that validates, normalizes or updates related data; a getter that computes a value or hides how it's stored. They're harmful noise when a class is just a bag of public data in disguise:

C++
// A getter and setter for every field adds ceremony but protects nothing.
class Point {
public:
    double x() const { return x_; }
    void set_x(double x) { x_ = x; }
    double y() const { return y_; }
    void set_y(double y) { y_ = y; }
private:
    double x_ = 0, y_ = 0;
};

// Any x and y are valid, so say so:
struct Point {
    double x = 0;
    double y = 0;
};

Better still, design operations that express intent rather than raw field updates. A bank account should have deposit and withdraw, not set_balance; a thermostat has raise and lower; an order has add_item and cancel, not set_status. This "tell, don't ask" style keeps the rules inside the class instead of spreading them across every caller.

Hide the representation, keep the interface

The deepest benefit of encapsulation is freedom to change the implementation. As long as the public interface stays the same, you can switch to a completely different representation and every caller keeps working, unchanged. The example below stores a time of day as minutes since midnight instead of separate hours and minutes. Users can't tell, but arithmetic becomes trivial.

C++ Changing the representation without changing the interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

If an earlier version stored hours_ and minutes_ publicly, switching to this representation would break every caller that touched them. With private data, the change touches only this class.

protected: access for derived classes

protected members are hidden from the outside world like private ones, but visible to classes that inherit from this one. It's meant for the interface between a base class and its derived classes.

C++
class Shape {
public:
    double area() const { return compute_area(); }
protected:
    virtual double compute_area() const = 0;    // derived classes implement this
    void log_change(const char* what) const;    // a helper they may call
private:
    int id_ = 0;                                // even derived classes can't touch this
};

Use protected mainly for member functions that derived classes need. Be careful with protected data: every derived class anyone ever writes can modify it, so the base class can no longer guarantee its invariants. Private data plus protected or public functions is almost always better. Inheritance and Access in Inheritance, Multiple and Virtual Inheritance cover the details.

Designing a good interface

A class's public section is a promise you'll have to keep. A few principles make it a good one:

  • Minimal but complete. Offer what users need and no more. Every public function is something you must keep working forever. Operations that can be written using the public interface often belong in free functions, not members.
  • Easy to use correctly, hard to use incorrectly. Prefer Meters{3.5} over a bare double, an enum class over a bool flag argument, and constructors that make invalid objects impossible to create.
  • Express intent. withdraw(amount) instead of set_balance(balance() - amount).
  • Const-correct. Every member function that doesn't change the object is const (const Member Functions and mutable), so const objects and const& parameters remain usable.
  • No leaks. Return values, const& or read-only views, never non-const handles to private data.
  • Private by default. Start with everything private and make things public only when a user needs them. Going from private to public is easy; the reverse breaks code.

Access control is a compile-time tool for correctness, not a security mechanism. Private data is still in memory and in the object's bytes, and determined code can reach it with casts or pointer tricks. Don't rely on private to protect passwords or keys from code running in the same process.

When a single outside function or class genuinely needs private access (for example operator<< for printing), C++ lets the class grant it explicitly with friend (Friend Functions and Classes).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside bool Money::is_more_than(const Money& other) const, can the code read other.cents_ if cents_ is private?

    C++ access control applies to code, not objects. A member function of a class can use the private members of every object of that class.
  2. 2. A class keeps a private std::vector<int> sorted. Which public member breaks the invariant?

    Returning a non-const reference lets callers modify the private vector directly, for example push_back an unsorted value. The other three only give read access.
  3. 3. Which statement about class invariants is correct?

    The invariant must hold whenever outside code can observe the object. It may be broken temporarily inside a member function, as long as it is restored before the function returns.
  4. 4. struct Color { int r, g, b; }; vs a class with private r, g, b and a getter and setter for each. When is the class version better?

    Private data plus setters pays off only when the setters protect an invariant. If every combination is valid, the plain struct is clearer.
  5. 5. Why should protected data members be used sparingly?

    Protected data is open to any class anyone derives later. Keeping data private and giving derived classes protected or public functions preserves the base class's control.

Summary

  • public members form the interface, private members the implementation, and protected members are shared with derived classes. A class starts private, a struct public.
  • Access is checked per class: member functions may use private members of any object of the same class.
  • An invariant is a rule every object obeys whenever others can see it. Constructors establish it, public member functions preserve it, and private data stops anyone else breaking it.
  • Never return non-const references or pointers to private data. Return values, const& or read-only views like std::span<const T>.
  • Getters and setters are worth writing when they validate, compute or hide representation; otherwise use a plain struct. Prefer operations that express intent.
  • Private data lets you change the representation without touching callers.
  • Keep interfaces minimal, const-correct and hard to misuse; access control is about correctness, not security.

Next: The this Pointer, where you'll see how a member function knows which object it's working on.