Menu
Coddy logo textTech

Access Specifiers in C++

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 34 of 104.

C++ provides three access specifiers that control who can access class members: public, protected, and private. These form the foundation of encapsulation.

class Account {
public:
    std::string ownerName;      // Accessible from anywhere
    
protected:
    double interestRate;        // Accessible in this class and derived classes
    
private:
    double balance;             // Accessible only within this class
};

Public members can be accessed from anywhere - inside the class, from derived classes, and from external code. Private members are the most restrictive, accessible only within the class itself. Protected sits in between - it acts like private to the outside world, but derived classes can access these members.

class Account {
private:
    double balance;
    
public:
    Account() : balance(0) {}
    
    void deposit(double amount) {
        balance += amount;    // OK - inside the class
    }
};

int main() {
    Account acc;
    acc.deposit(100);         // OK - deposit is public
    // acc.balance = 500;     // ERROR - balance is private
}

By default, all members in a class are private if no specifier is given. This encourages you to explicitly decide what should be exposed. The general practice is to make data members private and provide public methods to interact with them safely.

challenge icon

Challenge

Easy

Let's build a simple employee management system that demonstrates how access specifiers control who can access what. You'll create a class where some data is completely private, some is accessible to potential subclasses, and some is open to everyone.

You'll create two files to organize your code:

  • Employee.h: Define an Employee class that uses all three access specifiers to protect data appropriately:
    • Public: The employee's name (string) — this can be accessed from anywhere
    • Protected: The employee's department (string) — accessible within the class and by derived classes, but not from outside
    • Private: The employee's salary (double) — only accessible within the class itself
    • A constructor that takes name, department, and salary to initialize all three members
    • A public method getSalary() that returns the private salary value
    • A public method getDepartment() that returns the protected department value
    • A public method giveRaise(double amount) that increases the salary by the given amount (only if amount is positive)
    • A public method displayInfo() that prints the employee's information in the format: "Name: <name>, Department: <department>, Salary: "Name: <name>, Department: <department>, Salary: $<salary>"lt;salary>"
  • main.cpp: Demonstrate how access specifiers work by interacting with an Employee object. Read an employee's name, department, and salary from input (three separate lines), then:
    • Create an Employee with the input values
    • Print the employee's name directly by accessing the public member: "Direct access - Name: <name>"
    • Print the department using the getter: "Via getter - Department: <department>"
    • Print the salary using the getter: "Via getter - Salary: "Via getter - Salary: $<salary>"lt;salary>"
    • Give the employee a raise of 5000.0
    • Print "After raise:"
    • Call displayInfo() to show the updated information

Format all salary values with two decimal places using std::fixed and std::setprecision(2) from <iomanip>. Convert the salary input from string to double using std::stod().

The key insight here is that while you can access name directly from main, you cannot access department or salary directly — you must use the public getter methods. This is encapsulation in action: the class controls how its data is accessed and modified.

Cheat sheet

C++ provides three access specifiers to control access to class members:

  • public: Accessible from anywhere
  • protected: Accessible within the class and derived classes
  • private: Accessible only within the class itself
class Account {
public:
    std::string ownerName;      // Accessible from anywhere
    
protected:
    double interestRate;        // Accessible in this class and derived classes
    
private:
    double balance;             // Accessible only within this class
};

By default, all members in a class are private if no specifier is given.

Example demonstrating access control:

class Account {
private:
    double balance;
    
public:
    Account() : balance(0) {}
    
    void deposit(double amount) {
        balance += amount;    // OK - inside the class
    }
};

int main() {
    Account acc;
    acc.deposit(100);         // OK - deposit is public
    // acc.balance = 500;     // ERROR - balance is private
}

Best practice: Make data members private and provide public methods to interact with them safely.

Try it yourself

#include <iostream>
#include <string>
#include <iomanip>
#include "Employee.h"

using namespace std;

int main() {
    // Read input
    string name;
    string department;
    string salaryStr;
    
    getline(cin, name);
    getline(cin, department);
    getline(cin, salaryStr);
    double salary = stod(salaryStr);
    
    // Set precision for salary output
    cout << fixed << setprecision(2);
    
    // TODO: Create an Employee object with the input values
    
    // TODO: Print the employee's name by accessing the public member directly
    // Format: "Direct access - Name: <name>"
    
    // TODO: Print the department using the getter method
    // Format: "Via getter - Department: <department>"
    
    // TODO: Print the salary using the getter method
    // Format: "Via getter - Salary: $<salary>"
    
    // TODO: Give the employee a raise of 5000.0
    
    // TODO: Print "After raise:"
    
    // TODO: Call displayInfo() to show updated information
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming