Object-Oriented Programming (OOP) Basics
7 min read
Welcome to Module 7! 🚀
Up until now, you've likely been writing Procedural Code. This is where you write a list of instructions (functions) that operate on data (variables) floating around. It works for small programs, but as your software grows, procedural code can turn into "Spaghetti Code"—a tangled mess where everything touches everything else.
Object-Oriented Programming (OOP) is a paradigm based on the concept of "objects," which can contain data (attributes) and code (methods). It changes the mental model from "What is the logic?" to "Who are the actors in this system?"
Let's organize the chaos. 🧹
1. Classes and Objects: Blueprints and Instances 🏗️
The Definition
- Class: A user-defined data type that acts as a template for creating objects. It defines the structure (variables/data members) and behavior (functions/member functions).
- Object: An instance of a class. It is the actual entity created in memory based on the class definition.
The Problem
Imagine you are building a game with 500 enemies.
In procedural programming, you might create arrays:int enemyHealth[500];int enemyXPos[500];int enemyYPos[500];
To move enemy #42, you have to ensure you update index 42 in all those arrays. If you lose track, Enemy #42 might have the health of Enemy #43 but the position of Enemy #1. This is a maintenance nightmare. 😱
The Solution
We group the data (health, position) and the actions (move, attack) into a single unit called a Class.
Real World Simulation
Think of a Class as an architect's blueprint for a house. You cannot live in the blueprint. It just describes where the walls and windows go.
An Object is the actual house built from that blueprint. You can build 50 identical houses (objects) from one blueprint (class).
Code Example
In C++, a class is defined using the class keyword.
#include <iostream>
#include <string>
// The Blueprint (Class)
class Robot {
public:
// Data Members (Attributes)
std::string name;
int batteryLevel;
// Member Function (Method)
void introduce() {
std::cout << "Beep boop. I am " << name << ". Battery at " << batteryLevel << "%." << std::endl;
}
};
int main() {
// Creating Objects (Instances)
Robot bot1;
bot1.name = "Hal-9000";
bot1.batteryLevel = 100;
Robot bot2;
bot2.name = "Wall-E";
bot2.batteryLevel = 45;
// Using the objects
bot1.introduce(); // Output: Beep boop. I am Hal-9000...
bot2.introduce(); // Output: Beep boop. I am Wall-E...
return 0;
}Industry Standard: Class names usually start with a Capital letter (e.g.,
Robot,UserManager). Variable names inside are usually camelCase (e.g.,batteryLevel).
2. Access Specifiers: public, private, and protected 🔒
The Definition
Access specifiers define the scope and visibility of class members (variables and functions). They control who can see and modify the data.
The Problem
In the robot example above, bot1.batteryLevel = -5000; is valid code.
Technically, a battery cannot have negative charge. If you allow external code to modify your internal data directly, your object can enter an invalid state. This leads to bugs that are incredibly hard to track down.
The Solution
We restrict access. C++ provides three levels:
public: Accessible from anywhere (inside and outside the class).private: Accessible only from inside the class. This is the default for classes.protected: Accessible from inside the class and by child classes (used in Inheritance—we will cover this in a later module).
Code Example
class BankAccount {
private:
// Only the BankAccount class can touch this directly
double balance;
public:
// The world can call these functions
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
// We provide read-only access to the balance
double getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount;
// myAccount.balance = 1000000; // ❌ ERROR: 'balance' is private!
myAccount.deposit(500); // ✅ OK: deposit is public
// We interact with the data strictly through the public methods.
}Fun Fact: If you declare a
structin C++, all members arepublicby default. If you declare aclass, all members areprivateby default. That is literally the only technical difference between the two keywords in C++.
3. Constructors and Destructors: Birth and Death 👶💀
The Definition
- Constructor: A special method that runs automatically when an object is created. It has the same name as the class and no return type.
- Destructor: A special method that runs automatically when an object is destroyed (goes out of scope). It has the same name as the class preceded by a tilde (
~).
The Problem
If you create a Robot but forget to set the batteryLevel, C++ won't give it a value of 0. It will give it whatever random garbage binary data happened to be at that memory address (e.g., batteryLevel might be 2134215). This is undefined behavior.
The Solution
Use a Constructor to ensure an object is always ready to be used the moment it is born.
Industry Practice: Member Initializer Lists
In modern C++, we prefer "Member Initializer Lists" over setting values inside the constructor body. It is more efficient.
class Server {
private:
std::string region;
int maxConnections;
public:
// 1. Default Constructor (No arguments)
Server() : region("US-East"), maxConnections(100) {
std::cout << "Server starting with default settings..." << std::endl;
}
// 2. Parameterized Constructor (Custom arguments)
// Notice the syntax: : member(value), member(value)
Server(std::string reg, int conn) : region(reg), maxConnections(conn) {
std::cout << "Custom Server started in " << region << std::endl;
}
// 3. Destructor
~Server() {
// Use this to close files, database connections, or free memory
std::cout << "Server in " << region << " is shutting down..." << std::endl;
}
};
int main() {
{
Server s1; // Calls Default Constructor
Server s2("EU-West", 5000); // Calls Parameterized Constructor
}
// Both s1 and s2 go "out of scope" here.
// The Destructor is automatically called for both.
return 0;
}Imagination Time: Think of the Constructor as the factory assembly line ensuring the car has wheels before it leaves. Think of the Destructor as the scrapyard crusher ensuring the materials are recycled when the car is scrapped.
4. Encapsulation: Hiding Implementation Details 📦
The Definition
Encapsulation is the bundling of data and the methods that act on that data into a single unit (Class), and restricting direct access to some of an object's components.
The Problem
You have a NuclearReactor class. It has a variable coreTemperature. If you let a junior developer write reactor.coreTemperature = 99999; in the main() function, your digital city explodes. 💥
The Solution
You hide the data (private) and provide controlled access via Getters (Accessors) and Setters (Mutators).
Why go through the trouble?
- Validation: You can check input before assigning it.
- Read-Only: You can provide a Getter but no Setter.
- Flexibility: You can change how the data is stored internally without breaking the code that uses your class.
Practical Implementation
class SmartPhone {
private:
int volume; // 0 to 100
public:
// Constructor
SmartPhone() : volume(50) {}
// Getter (Accessor)
// 'const' ensures this function cannot modify the object
int getVolume() const {
return volume;
}
// Setter (Mutator)
void setVolume(int v) {
// Logic to prevent invalid states
if (v < 0) {
volume = 0;
} else if (v > 100) {
volume = 100;
} else {
volume = v;
}
}
};
int main() {
SmartPhone myPhone;
myPhone.setVolume(150); // The logic inside clamps this to 100
std::cout << "Volume: " << myPhone.getVolume() << std::endl; // Output: 100
// myPhone.volume = 150; // Compile Error! Encapsulation saves the day.
}🛠️ Industry Best Practices (The "Real" Way)
- Separate Files: In real projects, we don't dump everything in one file.
Robot.h: Contains the Class Declaration (the blueprint).Robot.cpp: Contains the Implementation (the function code).main.cpp: Uses the class.
- Const Correctness: If a function (like a Getter) does not modify the object, always mark it as
const. This helps the compiler optimize code and prevents logic errors. - Struct vs Class: Use
structonly for Plain Old Data (POD)—objects that are just bundles of data without complex logic or private members. Useclassfor everything else.
Summary Checklist ✅
- Class: The code template.
- Object: The living thing in memory.
- Private: Keep your data here.
- Public: Put your interface methods here.
- Constructor: Setup your data here (use initializer lists!).
- Destructor: Clean up here.
- Encapsulation: Protect your data behind functions.
You have now taken your first step into a larger world. Instead of writing scripts, you are now designing systems.
📚 References & Further Reading
- Microsoft C++ Docs (Classes): learn.microsoft.com/cpp/cpp/classes-and-structs-cpp
- Constructors (cppreference): en.cppreference.com/w/cpp/language/constructor
- Access Specifiers: learn.microsoft.com/cpp/cpp/member-access-control-cpp
- Encapsulation Best Practices: isocpp.org/wiki/faq/classes-and-objects
Challenge
You are tasked with designing a SmartThermostat class in C++ that encapsulates its data and provides a controlled public interface. This exercise will test your understanding of classes, constructors, destructors, access specifiers, encapsulation, and const-correctness.
Requirements:
- Define a class named
SmartThermostat. - Private Members: The class must have the following private data members:
double currentTemperature: The current temperature reading.double targetTemperature: The desired temperature.double minTemperature: The minimum allowed target temperature.double maxTemperature: The maximum allowed target temperature.Mode operatingMode: The current mode of the thermostat, using the providedenum Mode.
- Public Interface:
- Constructor: A parameterized constructor that accepts initial values for
currentTemperature,targetTemperature,minTemperature, andmaxTemperature. It must use a member initializer list for initialization. TheoperatingModeshould be initialized toMode::Off. - Destructor: A simple destructor. While it won't perform complex cleanup in this environment, its presence is required for complete class design.
- Setters: A public method
setTarget(double newTarget)that updatestargetTemperature. It must validate thatnewTargetis within theminTemperatureandmaxTemperaturerange. If the new target is invalid, thetargetTemperatureshould not be changed. - Getters: Implement
constpublic getter methods forgetCurrentTemperature(),getTargetTemperature(), andgetOperatingMode(). - Logic Method: A public method
updateStatus()which checks thecurrentTemperatureagainst thetargetTemperature. If the current is more than 1 degree below the target, setoperatingModetoMode::Heating. If it's more than 1 degree above, set it toMode::Cooling. Otherwise, set it toMode::Off. - Reporting Method: A
constpublic methodgetStatusReport()that returns astd::stringsummarizing the thermostat's state.
- Constructor: A parameterized constructor that accepts initial values for
Expected result
Your final code should be a complete C++ class definition for SmartThermostat that fulfills all the requirements specified in the instructions.
A correct solution will feature:
- A class named
SmartThermostat. - All data members (
currentTemperature,targetTemperature,minTemperature,maxTemperature,operatingMode) declared under theprivateaccess specifier. - A public parameterized constructor that correctly initializes all members using a member initializer list.
- A public destructor,
~SmartThermostat(). - A public
setTarget(double newTarget)method that includes validation logic to ensure the new target is within the min/max range. - Public,
const-qualified getter methods:getCurrentTemperature(),getTargetTemperature(), andgetOperatingMode(). - A public
updateStatus()method containing the specified logic to change theoperatingMode. - A public,
const-qualifiedgetStatusReport()method that returns astd::string.