01 / 20

Encapsulation
in C++

Learn how to protect your data with private members and expose controlled access through public methods: the foundation of robust object-oriented design.

C++ Object-Oriented Programming

What Is Encapsulation?

Encapsulation is the practice of bundling data and the functions that operate on that data into a single unit (a class), while restricting direct access to the internal state. Only carefully chosen public methods can read or modify the hidden data.

Why Does It Matter?

★ Data Protection
Prevents outside code from putting your object into an invalid state.
★ Easier Maintenance
You can change internal implementation without breaking code that uses your class.
★ Clear Contracts
Public methods define a clear API: users know exactly what they can do.

The Capsule Model

class BankAccount private string ownerName double balance int accountId public getBalance() deposit(amount) withdraw(amount) getOwner() External Code

The Three Access Specifiers

private
Accessible only inside the class itself. This is the default for class members in C++.
public
Accessible from anywhere: other classes, functions, or main(). Forms the external API.
protected
Like private, but also accessible by derived (child) classes. Used in inheritance.

The Core Rule of Encapsulation

This creates a controlled gateway. Inside a setter, you can add validation (e.g., reject a negative bank balance). Inside a getter, you can add formatting or computation. The caller never knows how data is stored internally.

// The pattern: class MyClass { private: int data; // hidden public: int getData() { return data; } void setData(int d) { data = d; } };

Getters and Setters

main() public methods getBalance() setBalance(val) deposit(amt) private balance owner ✕ Direct access blocked

Getters return a copy of private data. Setters accept a new value, validate it, then update the private member. External code never touches the variable directly.

class vs struct

class struct
Default access private public
Encapsulation Encouraged by default Must add private: manually
Convention Objects with behavior Simple data bundles (PODs)
Inheritance default private public

How to Apply Encapsulation

1
Identify the data. List every piece of internal state your class needs (e.g., name, balance, score).
2
Make all data private. Place each member under the private: specifier.
3
Write public getters. Return the data (by value or const reference) so external code can read it.
4
Write public setters with validation. Check that incoming values are valid before storing them.
5
Initialize via the constructor. Set safe defaults so the object is never in a broken state.

Example 1: Student Class

class Student { private: string name; int grade; // 0-100 public: // Constructor Student(string n, int g) : name(n) { setGrade(g); // reuse validation } // Getter string getName() const { return name; } int getGrade() const { return grade; } // Setter with validation void setGrade(int g) { if (g < 0) g = 0; if (g > 100) g = 100; grade = g; } };

Example 2: BankAccount

class BankAccount { private: double balance; public: BankAccount(double initial) { balance = (initial >= 0) ? initial : 0; } double getBalance() const { return balance; } bool deposit(double amt) { if (amt <= 0) return false; balance += amt; return true; } bool withdraw(double amt) { if (amt <= 0 || amt > balance) return false; balance -= amt; return true; } };

Example 3: TemperatureSensor

class TemperatureSensor { private: double celsius; public: TemperatureSensor(double c) : celsius(c) {} double getCelsius() const { return celsius; } double getFahrenheit() const { return celsius * 1.8 + 32; } void setCelsius(double c) { if (c < -273.15) c = -273.15; celsius = c; } };

The Power of Validation

Without Encapsulation acct.balance = -9999; student.grade = 500; sensor.temp = -9999; ✕ All invalid, all allowed With Encapsulation withdraw(-9999) → false setGrade(500) → clamped setCelsius(-9999) → fixed ✓ All caught, all safe

Common Mistakes

✕ Everything Public
Making all members public defeats the purpose. External code can corrupt your data freely.
✕ No Validation
Writing setters that blindly assign values: void setAge(int a){age=a;} without checking the input.
✕ Returning References
Returning a non-const reference to private data lets callers modify it, bypassing your setters entirely.

Summary Checklist

Principle Do Don't
Data members private public
Getters Return by value or const ref Return non-const reference
Setters Validate before assigning Blindly assign
Constructor Set safe defaults Leave members uninitialized
Keyword Use class for encapsulated types Use struct for complex objects

Question 1 of 5

What is the default access specifier for members of a C++ class?

Question 2 of 5

Which of the following best describes encapsulation?

Question 3 of 5

Given the class below, what is the output?

class Box { private: int size; public: Box(int s) { size = (s > 0) ? s : 1; } int getSize() const { return size; } }; // In main(): Box b(-5); cout << b.getSize();

Question 4 of 5

Why is returning a non-const reference from a getter considered a violation of encapsulation?

Question 5 of 5

A TemperatureSensor stores data internally in Celsius. A developer changes the internal storage to Kelvin but keeps the same public getters. What happens to code that calls getCelsius()?