← Back to C++ Course | Chapter 8: OOP Core | Lesson 4 of 14

C++ Access Specifiers

Public Specifier

Members declared as public can be accessed from anywhere in the program, both from inside the class's own methods and from any external code that holds an object of that type. Public members form the class's external contract with the rest of the program.

Example: Public Specifier

cpp
#include <iostream>

class Box {
public:
	int size = 5;
};

int main() {
	Box b;
	std::cout << b.size << std::endl; // accessible from outside
	return 0;
}

Private Specifier

Members declared as private can only be accessed by member functions of that same class — they're completely hidden from any code outside it. This is the primary mechanism C++ gives you to protect an object's internal data from accidental or unauthorized modification.

Example: Private Specifier

cpp
#include <iostream>

class Box {
private:
	int size = 5;
public:
	int getSize() { return size; } // only class methods can reach "size" directly
};

int main() {
	Box b;
	std::cout << b.getSize() << std::endl;
	return 0;
}

Getters and Setters

Getters and setters are public functions that provide controlled access to otherwise-private variables: a getter retrieves the current value, while a setter can validate incoming data before allowing it to update the private field, rejecting invalid input at the boundary.

Example: Getters and Setters

cpp
#include <iostream>

class Account {
private:
	double balance = 0;
public:
	void setBalance(double amount) { balance = amount; }
	double getBalance() { return balance; }
};

int main() {
	Account acc;
	acc.setBalance(100);
	std::cout << acc.getBalance() << std::endl;
	return 0;
}

Protected Specifier

Protected members behave like private members for the outside world — completely hidden — but unlike private members, they remain accessible to any class that inherits from the one that declares them. This is what lets a derived class build on its parent's internal state.

Example: Protected Specifier

cpp
#include <iostream>

class Animal {
protected:
	int age = 1;
};

class Dog : public Animal {
public:
	void showAge() { std::cout << age << std::endl; } // accessible in a derived class
};

int main() {
	Dog d;
	d.showAge();
	return 0;
}

Default Access in Struct vs Class

The only structural difference between a struct and a class in C++ is their default access level: class members are private by default, while struct members are public by default. Everything else — inheritance, methods, constructors — works identically on both.

Example: Default Access in Struct vs Class

cpp
#include <iostream>

struct Point { int x; }; // members public by default
class Box { int size; }; // members private by default

int main() {
	Point p;
	p.x = 5;
	std::cout << p.x << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.