AlgoDaily

Object-Oriented Programming in C++

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

From Functions To Objects

Why OOP matters now

In Introduction to C++, you practiced variables, control flow, functions, and the compile-then-run workflow. That gives us the building blocks.

Now we’ll start organizing those blocks into objects: values that carry both:

  • state: data they remember
  • behavior: functions that operate on that data

As a JS developer, you’ve likely used objects and classes already. C++ OOP will feel familiar, but with stronger compile-time rules around types, visibility, and object layout.

Think of an electronics project: a Sensor object might store its latest reading and expose functions like read() or calibrate(). The rest of your program doesn’t need to know every wire-level detail.

From Functions To Objects

Classes And Objects

A class is a blueprint

A class describes what an object knows and what it can do.

An object is a concrete instance of that class.

JS analogy:

  • class Speaker { ... } is the recipe
  • Speaker kitchenSpeaker; is one actual speaker

In C++, class members are usually split into:

  • private: internal details
  • public: the interface other code can use

That separation is a major part of C++ OOP.

```cpp
#include <iostream>
#include <string>

class Speaker {
private:
    int volume;

public:
    Speaker() {
        volume = 5;
    }

    void turnUp() {
        volume++;
    }

    void play(const std::string& song) {
        std::cout << "Playing " << song
                  << " at volume " << volume << "\n";
    }
};

int main() {
    Speaker livingRoomSpeaker;
    livingRoomSpeaker.play("lo-fi beat");

    livingRoomSpeaker.turnUp();
    livingRoomSpeaker.play("funk groove");

    return 0;
}
```

Private Means What

In a C++ class, what does private primarily mean?

Protect The Invariants

Encapsulation is about trust boundaries

In web apps, you probably avoid letting random code mutate important state directly. Same idea here.

A class can keep data private and expose safe operations through public methods.

That lets the class preserve invariants: rules that should always stay true.

For example, a basketball scoreboard should not allow negative points. Instead of exposing points directly, we expose a method that validates updates.

Also notice the constructor syntax below:

Scoreboard() : points(0) {}

That : points(0) part is an initializer list. It initializes members before the constructor body runs.

```cpp
#include <iostream>

class Scoreboard {
private:
    int points;

public:
    Scoreboard() : points(0) {}

    void addPoints(int amount) {
        if (amount > 0) {
            points += amount;
        }
    }

    int getPoints() const {
        return points;
    }
};

int main() {
    Scoreboard homeTeam;

    homeTeam.addPoints(3);
    homeTeam.addPoints(-100); // ignored

    std::cout << "Home team points: "
              << homeTeam.getPoints() << "\n";

    return 0;
}
```

Constructor Return Type

True or false: In C++, a constructor declares a return type such as void, int, or the class type.

Inheritance Models Is A

Reuse by specialization

Inheritance lets one class build on another.

Use it when the relationship is genuinely is-a:

  • A SmartLight is a Device
  • A Guitar is an Instrument
  • A PointGuard is a BasketballPlayer

The base class contains shared behavior. The derived class adds or customizes behavior.

In C++, public inheritance looks like this:

class SmartLight : public Device {
    // extra SmartLight behavior
};

Read it as: “SmartLight inherits publicly from Device.”

Be careful not to use inheritance just because two things share a few fields. If the relationship is more like “has-a,” composition is usually cleaner.

Inheritance Models Is A

Inheritance Keyword

Fill in the blank:

To model “SmartLight is a Device” while keeping Device's public interface public, write:

class SmartLight : ____ Device

Polymorphism In Practice

Same interface, different behavior

Polymorphism means code can work with a general type while each specific type responds in its own way.

This is especially useful when you want one function to handle many related objects.

In C++, runtime polymorphism usually needs:

  • a base class function marked virtual
  • derived class functions marked override
  • access through a base reference or pointer

Here, perform() accepts any Instrument, but the actual sound depends on the concrete object passed in.

```cpp
#include <iostream>

class Instrument {
public:
    virtual void play() const {
        std::cout << "The instrument makes a sound.\n";
    }
};

class Guitar : public Instrument {
public:
    void play() const override {
        std::cout << "Guitar: strum strum!\n";
    }
};

class DrumKit : public Instrument {
public:
    void play() const override {
        std::cout << "Drums: boom bap!\n";
    }
};

void perform(const Instrument& instrument) {
    instrument.play();
}

int main() {
    Guitar guitar;
    DrumKit drums;

    perform(guitar);
    perform(drums);

    return 0;
}
```

Virtual Dispatch

Suppose a base class function is not marked virtual, and you call it through a base-class reference. What should you generally expect?

OOP Mental Model

What to keep from this lesson

C++ OOP gives you tools for building larger programs without turning every function into a tangled utility script.

Key ideas:

  • Class: blueprint for objects
  • Object: instance with state and behavior
  • Encapsulation: protect internal state behind a public interface
  • Constructor: initializes an object into a valid starting state
  • Inheritance: model true is-a relationships
  • Polymorphism: let different derived objects respond through a shared base interface

Compared with JS, C++ asks you to be more explicit. That extra structure pays off when programs grow and when correctness matters.

Next, we’ll move from modeling objects in memory to Working with Files in C++, where your programs can read and write data beyond a single run.

OOP Mental Model

Open interactive view →