Search⌘ K
AI Features

Classes, Encapsulation, and Access Control

Explore how organizing data with classes and encapsulation improves safety and reliability in C++ programs. This lesson teaches using access specifiers like private and public to protect object state, enforce invariants, and design clean interfaces. You'll understand how to prevent invalid data changes and keep internal workings hidden while allowing controlled interaction.

Up until now, we have learned how to store values in variables and change them using functions. This works for small programs, but it becomes unsafe as programs grow. A variable can be changed to any value, even an invalid one, because nothing protects it. This can lead to mistakes and inconsistent data. To avoid this, we need a way to keep data and the code that controls it together in one place. This idea is called object-oriented programming (OOP). In C++, we do this using a class.

Structs: Grouping data

Before we jump into powerful objects, let's look at the simplest way to group data: the struct (structure).

A struct is a user-defined type that bundles related variables together. By default, everything inside a struct is public, which means anyone can read or write the data directly.

Let's build a simple banking system.

C++ 23
#include <iostream>
#include <string>
struct BankAccount {
std::string owner;
double balance;
}; // Semicolon is required!
int main() {
// 1. Create an instance (object) of the struct
BankAccount account;
// 2. We can access members directly because they are public by default
account.owner = "Alice";
account.balance = 100.0;
std::cout << account.owner << " has $" << account.balance << "\n";
// THE PROBLEM: No safety. We can break the logic easily
account.balance = -5000.0; // Invalid state!
std::cout << "Broken Balance: " << account.balance << "\n";
return 0;
}

Let’s break ...