Learn C++ · 7/15

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.

cpp
#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:

  1. public: Accessible from anywhere (inside and outside the class).
  2. private: Accessible only from inside the class. This is the default for classes.
  3. protected: Accessible from inside the class and by child classes (used in Inheritance—we will cover this in a later module).

Code Example

cpp
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 struct in C++, all members are public by default. If you declare a class, all members are private by 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.

cpp
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?

  1. Validation: You can check input before assigning it.
  2. Read-Only: You can provide a Getter but no Setter.
  3. Flexibility: You can change how the data is stored internally without breaking the code that uses your class.

Practical Implementation

cpp
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)

  1. 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.
  2. 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.
  3. Struct vs Class: Use struct only for Plain Old Data (POD)—objects that are just bundles of data without complex logic or private members. Use class for 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

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:

  1. Define a class named SmartThermostat.
  2. 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 provided enum Mode.
  3. Public Interface:
    • Constructor: A parameterized constructor that accepts initial values for currentTemperature, targetTemperature, minTemperature, and maxTemperature. It must use a member initializer list for initialization. The operatingMode should be initialized to Mode::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 updates targetTemperature. It must validate that newTarget is within the minTemperature and maxTemperature range. If the new target is invalid, the targetTemperature should not be changed.
    • Getters: Implement const public getter methods for getCurrentTemperature(), getTargetTemperature(), and getOperatingMode().
    • Logic Method: A public method updateStatus() which checks the currentTemperature against the targetTemperature. If the current is more than 1 degree below the target, set operatingMode to Mode::Heating. If it's more than 1 degree above, set it to Mode::Cooling. Otherwise, set it to Mode::Off.
    • Reporting Method: A const public method getStatusReport() that returns a std::string summarizing the thermostat's state.

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 the private access 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(), and getOperatingMode().
  • A public updateStatus() method containing the specified logic to change the operatingMode.
  • A public, const-qualified getStatusReport() method that returns a std::string.
cpp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.