⚡C++IntermediateLesson 25 of 50CamboFreelanceJune 19, 2026
C++ Access Specifiers
Understand C++ access specifiers: public, private, and protected. Learn how they control class member visibility and enforce data hiding.
Intermediate6 min readLesson 25 of 50
public, private, protected
Specifier
Accessible From
public
Anywhere — inside and outside the class
private
Only inside the class (default for class members)
protected
Inside the class and derived (child) classes
#include <iostream>
using namespace std;
class Employee {
private:
double salary; // cannot be accessed directly from outside
public:
string name;
Employee(string n, double s) : name(n), salary(s) { }
double getSalary() { return salary; }
void setSalary(double s) { if (s > 0) salary = s; }
};
int main() {
Employee e("Alice", 5000);
cout << e.name << " earns $" << e.getSalary() << endl;
e.setSalary(5500);
cout << "New salary: $" << e.getSalary() << endl;
// e.salary = -999; // ERROR — private member
return 0;
}
Output:
Alice earns $5000
New salary: $5500
Exercise
Create a Temperature class with a private celsius field. Add public methods to set (validate >= -273.15), get celsius, and get fahrenheit (F = C * 9/5 + 32).
Show Solution
#include <iostream>
using namespace std;
class Temperature {
private:
double celsius;
public:
void setCelsius(double c) {
if (c >= -273.15) celsius = c;
}
double getCelsius() { return celsius; }
double getFahrenheit() { return celsius * 9.0/5.0 + 32; }
};
int main() {
Temperature t;
t.setCelsius(100);
cout << t.getCelsius() << "C" << endl;
cout << t.getFahrenheit() << "F" << endl;
return 0;
}
Quiz
Which access specifier restricts access to the class itself only?
A) public
B) protected
C) private
D) internal
Answer
C) private
What is the default access specifier for class members in C++?
A) public
B) protected
C) private
D) internal
Answer
C) private — unlike struct, where the default is public.
Summary
public — accessible everywhere.
private — accessible only inside the class (default).
protected — accessible inside the class and subclasses.