Access Specifiers in C++: A Friendly Guide to Public, Private, and Protected

2025-09-09

Access specifiers in C++ are keywords that control the accessibility of class members (variables, methods, and nested classes). They determine which parts of a program can access the members of a class. The three main types are public, private, and protected.

Here's a quick breakdown

public
Members declared as public are accessible from anywhere. Think of them as the class's interface—what other parts of your code use to interact with the class. This is where you'd put methods that expose the functionality of your class.

private
Members declared as private can only be accessed from within the same class. They are hidden from the outside world. This is where you store internal data and helper methods that are essential for the class's operation but shouldn't be directly modified by outside code.

protected
Members declared as protected are similar to private but with one key difference
they can be accessed by the class itself and by any classes that inherit from it. This is useful for building a hierarchy of related classes.

The Problem
A common mistake for beginners is to make all class members public. This exposes the internal state of your objects, leading to a lack of control and making your code difficult to maintain and debug. Anyone can change a public member directly, bypassing any validation logic you might have in your methods.

Example of the Problem

class Car {
public:
    int speed;
    int gear;

    void accelerate() {
        speed += 10;
    }
};

int main() {
    Car myCar;
    myCar.speed = 1000; // Directly changing the speed
    // This bypasses the accelerate method's intended logic
    return 0;
}

The Solution
Use private to encapsulate data. This is a core principle of Object-Oriented Programming (OOP) known as encapsulation. You should expose functionality through public methods and keep the data private.

Alternative Code Example

class Car {
private:
    int speed;
    int gear;

public:
    Car() : speed(0), gear(0) {} // Constructor to initialize state

    void accelerate() {
        if (speed < 200) { // Add a boundary check
            speed += 10;
        }
    }

    // A public "getter" method to read the speed
    int getSpeed() const {
        return speed;
    }
};

int main() {
    Car myCar;
    myCar.accelerate(); // The correct way to change speed
    // myCar.speed = 1000; // This will now cause a compiler error
    return 0;
}

The Problem
Sometimes, people use protected when private is the better choice. protected members are only needed when you are working with inheritance. If your class isn't designed to be a base class that other classes will inherit from, protected is not serving its purpose and can be confusing.

Example of the Problem

class Account {
protected:
    double balance; // 'protected' is not needed here if there's no inheritance

public:
    Account(double initialBalance) : balance(initialBalance) {}

    void deposit(double amount) {
        balance += amount;
    }
};

The Solution
If the data is only intended to be used by the class itself, use private. This strengthens encapsulation and makes the class's purpose clearer.

Alternative Code Example

class Account {
private:
    double balance; // Correctly using 'private' for internal data

public:
    Account(double initialBalance) : balance(initialBalance) {}

    void deposit(double amount) {
        balance += amount;
    }

    double getBalance() const {
        return balance;
    }
};

The Problem
C++ classes have a default access specifier. If you don't specify one, all members are private by default. This can lead to unexpected compiler errors if you forget to add public before the methods you want to expose.

Example of the Problem

class Light {
    bool isOn; // This is 'private' by default

    void toggle() { // This is also 'private' by default
        isOn = !isOn;
    }
};

int main() {
    Light myLight;
    // myLight.toggle(); // This will not compile because toggle() is private
    return 0;
}

The Solution
Always be explicit with your access specifiers to avoid confusion. It's good practice to place your public members first, followed by protected and then private.

Alternative Code Example

class Light {
public: // Explicitly marking the public interface
    void toggle() {
        isOn = !isOn;
    }

private: // Explicitly marking the private data
    bool isOn;
};

int main() {
    Light myLight;
    myLight.toggle(); // Now this works as expected
    return 0;
}

By understanding and correctly applying public, private, and protected, you can write cleaner, safer, and more maintainable C++ code. Remember that the goal is to protect your class's internal state and expose only what's necessary to the outside world.


cpp



A C++ Developer's Guide to drop_view::begin Performance

When you're using std::ranges::drop_view::begin, you might run into a few tricky situations. One of the most common is when you use a drop_view on a non-random_access_range


Demystifying Freestanding vs. Hosted C++ Implementations

First, let's quickly clarify the two concepts.Hosted implementation This is the standard C++ environment you're likely familiar with


Troubleshooting std::filesystem::hard_link_count in C++

First, a quick refresher. std::filesystem::hard_link_count returns the number of hard links to a file. A hard link is a directory entry that associates a name with a file on a file system



Understanding C++ std::endian: Common Issues and Solutions

std::endian is a C++20 feature that helps you determine the endianness of the platform your program is running on. Endianness refers to the order in which a sequence of bytes is stored in computer memory


Mastering File I/O: A Deep Dive into C++ std::fseek and Its Modern Alternatives

std::fseek is a C-style function used to move the file position indicator for a given file stream. While it's a powerful tool


Troubleshooting std::acos in C++: Common Errors and Workarounds

Input Out of Range The most frequent problem is passing a value greater than 1 or less than -1 to std::acos. When this occurs


The N-Group Trap: Sentinel Logic in C++ adjacent_transform_view Explained

Let's break down the common troubles and look at some alternative approaches for the operator== involving ranges::adjacent_transform_view::sentinel


Exception Handling in C++: Why std::uncaught_exception is Obsolete

The function std::uncaught_exception() is a diagnostic tool in the C++ standard library that returns true if an exception is currently in the process of being thrown


C++ std::chrono::get_tzdb: Common Pitfalls and Alternatives

The most common problem people face with std::chrono::get_tzdb is that it can fail to load the time zone database. This often happens for a few key reasons


Demystifying C++ Ranges: A Guide to std::ranges::join_view::begin

std::ranges::join_view is a super useful C++20 range adaptor that lets you flatten a range of ranges. Think of it like taking a list of lists and creating a single