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
EasyLet'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 anEmployeeclass 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>"
- Public: The employee's
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
Employeewith 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
- Create an
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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container