Thuta Learning
C++
AdvancedProgrammingBeginner

OOP Intro

C++Lesson 1825 min

What you'll walk away with

  • Tell a class (the blueprint) from an object (the thing built from it)
  • Read a class with data members and member functions, and explain why every object has its own state
  • Explain what an invariant is and why private data protects it
  • Say what encapsulation, inheritance and polymorphism mean, and tell "is-a" from "has-a"

Explain it simply

Explain it simply

Object-oriented programming (OOP) means building a program out of small parts that each look after their own data. Think of a car: it has data (its brand, its current speed, its top speed) and things it can do (accelerate, brake, report its speed). Instead of keeping those facts in loose variables scattered around the program, you bundle the data and the actions into one unit and give that unit a name.

In C++ the blueprint for such a unit is a class, and each thing built from the blueprint is an object. One Car class can produce a hundred cars, and each car has its own speed. The unit also keeps its data behind a small counter: the rest of the program asks the car to accelerate instead of reaching in and changing the speed itself.

Problem → Why → Solution

The problem: a car scattered across loose variables

Say you want to store the brand, speed and top speed of two cars. Without OOP, the usual result is three parallel vectors, where index 0 means one car and index 1 means the other. In the code below, accelerate() never checks the top speed, so the Toyota is recorded at 150 when it can only do 120. main can also set a speed to -40 directly, and one pop_back() leaves the three vectors with different lengths. Everything compiles, and the compiler stops none of these mistakes.

loose_cars.cpp
#include <iostream>
#include <string>
#include <vector>

// Data and behaviour live far apart, and nothing guards the data.
std::vector<std::string> brands{"Toyota", "Mazda"};
std::vector<int> speeds{0, 0};
std::vector<int> maxSpeeds{120, 200};

void accelerate(int car, int amount) {
    speeds[car] += amount;          // no check against maxSpeeds
}

int main() {
    accelerate(0, 150);             // Toyota now "goes" 150, above its limit of 120
    speeds[1] = -40;                // any code can write nonsense directly
    maxSpeeds.pop_back();           // the parallel vectors no longer line up
    std::cout << brands[0] << " " << speeds[0] << '\n';
}

Why does the data need protection?

Nothing in this code says "speed must stay between zero and the top speed", and nobody enforces it. As the program grows there are more places to go wrong, and when hunting a bug you must check every line that touches speeds. OOP puts the rule in the same class as the data: with the data private, only the class's own functions can break the rule, so only those few functions need checking.

Core concept: classes, objects and invariants

A class describes a new type: which data its objects hold (data members) and which operations they offer (member functions). An object is one concrete value of that type, with its own copy of the data members. In the example below, city and sport are two Car objects, and accelerating one never touches the other. In C++ objects are ordinary values: they can live on the stack, inside a vector or inside another object, and they are destroyed automatically when their scope ends, just like the RAII objects of the previous lessons.

text
One class, many objects
-----------------------
            class Car   (the blueprint)
      data: brand_, maxSpeed_, speed_
      does: accelerate(), brake(), report()
                     |
           +---------+----------+
           |                    |
      Car city              Car sport
      brand_    "Toyota"    brand_    "Mazda"
      maxSpeed_ 120         maxSpeed_ 200
      speed_    0           speed_    0      each object: its own copy

The most important idea is the invariant: a fact about the data that must always be true, such as 0 <= speed <= maxSpeed. A class protects its invariants by making the data private and offering only member functions that keep the fact true; this is called encapsulation. With public data, every line in the program could break the invariant, so you must review all of them; with private data only the class's member functions can break it, so only those need review. The compiler enforces this: writing city.speed_ = -40 from outside fails with error: 'int Car::speed_' is private within this context.

The only difference between class and struct is the default access: members of a class are private by default, members of a struct are public. That is why a struct is the usual choice for a small bundle of data with no invariant, and a class for a type that must guard a rule. Objects relate to each other in two ways. "A car has an engine" is a has-a relationship and is expressed with a data member; only "a circle is a shape", an is-a relationship, is expressed with inheritance.

IdeaWhat it meansWhere you meet it
Encapsulationdata hidden, invariants guarded by member functionsAccess Specifiers
Inheritancea new class extends an existing one (is-a)Inheritance
Polymorphismone call, behaviour chosen by the real objectPolymorphism

When an object is first created, a constructor makes sure its data starts out valid; the Constructors lesson covers that in detail. The goal of this lesson is just to show what the next lessons are for.

Mental model: one blueprint, many objects with their own state
  1. Class = blueprint, object = built thing
  2. Data members hold each object's state
  3. Member functions are the only way in
  4. The class keeps its invariants true

Ask the object to act instead of reaching in to change its data, so it can enforce its own rules.

General pattern

cpp
class TypeName {
public:
    TypeName(params);           // sets up a valid object
    ReturnType action(params);  // behaviour: may change the state
    ReturnType query() const;   // behaviour: only reads the state
private:
    Type member_;               // state hidden from outside code
};

TypeName object(args);          // build an object from the blueprint
object.action(args);            // ask it to do something

The public part is the interface offered to the outside, and the private part hides the state. A function that only reads is marked const, so it can also be called on a const object. The trailing _ on member names is just a naming habit that makes data members easy to spot.

Example: two Car objects, two separate states

This Car class stores the brand, the top speed and the current speed as private data. accelerate() and brake() change the speed and keep it between 0 and maxSpeed on their own, while report() only reads. main creates two cars, asks the first to accelerate past its limit and later to brake past zero, and the invariant never breaks.

car.cpp
#include <iostream>
#include <string>
#include <utility>

class Car {
public:
    Car(std::string brand, int maxSpeed)
        : brand_(std::move(brand)), maxSpeed_(maxSpeed) {}

    void accelerate(int amount) {
        speed_ += amount;
        if (speed_ > maxSpeed_) speed_ = maxSpeed_;
    }

    void brake(int amount) {
        speed_ -= amount;
        if (speed_ < 0) speed_ = 0;
    }

    void report() const {
        std::cout << brand_ << " is going " << speed_ << " km/h\n";
    }

private:
    std::string brand_;
    int maxSpeed_;
    int speed_ = 0;
};

int main() {
    Car city("Toyota", 120);
    Car sport("Mazda", 200);

    city.accelerate(150);
    sport.accelerate(90);
    city.report();
    sport.report();

    city.brake(500);
    city.report();
}

Code breakdown

  1. Lines 5-28class Car {

    The whole class is the blueprint. The public section (a constructor and three functions) is what the outside can use, and the private section hides the state.

  2. Lines 7-8: brand_(std::move(brand)), maxSpeed_(maxSpeed) {}

    When an object is created, the constructor stores the brand and the top speed in the data members. The syntax is explained in the Constructors lesson; for now, read it as "store the arguments in the members".

  3. Line 12if (speed_ > maxSpeed_) speed_ = maxSpeed_;

    This line guards the invariant. Even when 150 is requested, the speed stops at 120. Nobody else can touch speed_, so the rule lives in exactly one place.

  4. Line 20void report() const {

    const promises that this function does not change the object; functions that only read should be marked this way.

  5. Lines 24-27private:

    The three pieces of state live here, and the compiler rejects any attempt to write to them from outside the class. speed_ = 0 means every new object starts at zero.

  6. Lines 31-34Car city("Toyota", 120);

    This creates two Car objects. city.accelerate(150) changes only city's speed_; sport has its own copy, which ends at 90.

You should see
Toyota is going 120 km/h
Mazda is going 90 km/h
Toyota is going 0 km/h

Let the class defend its own invariants

A well-designed class deals with bad values inside itself instead of passing them on to the caller. The Thermostat below keeps its target temperature between 10 and 30; when a caller asks for 75 or -5, it gets the nearest allowed value. The getter target() is const, so it only reads and hands back a value, and setTarget() is the single way to change it. That means that wherever this object is used in the program, you can trust that its target is valid.

thermostat.cpp
#include <iostream>

class Thermostat {
public:
    void setTarget(int degrees) {
        if (degrees < 10) degrees = 10;
        if (degrees > 30) degrees = 30;
        target_ = degrees;
    }
    int target() const { return target_; }

private:
    int target_ = 20;
};

int main() {
    Thermostat hall;
    std::cout << hall.target() << '\n';   // 20
    hall.setTarget(75);
    std::cout << hall.target() << '\n';   // 30
    hall.setTarget(-5);
    std::cout << hall.target() << '\n';   // 10
}

A first look: is-a and polymorphism

A Square and a Rectangle are both shapes and both have an area, but they compute it differently. If both derive from a Shape base class (is-a), one piece of code can hold any shape as a Shape and call area(); which version actually runs is decided by the real object. That is polymorphism, and it works because of virtual and override. The virtual destructor is there so that deleting a derived object through a base pointer is correct. The Inheritance and Polymorphism lessons explain these details; for now, just look at the shape of the idea.

shapes.cpp
#include <iostream>
#include <memory>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

class Square : public Shape {
public:
    explicit Square(double side) : side_(side) {}
    double area() const override { return side_ * side_; }
private:
    double side_;
};

class Rectangle : public Shape {
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    double area() const override { return w_ * h_; }
private:
    double w_, h_;
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Square>(3));
    shapes.push_back(std::make_unique<Rectangle>(2, 5));

    for (const auto& shape : shapes) {
        std::cout << "area: " << shape->area() << '\n';   // area: 9, then area: 10
    }
}

In real projects

Where this shows up in real projects

The C++ types you already use are classes: std::string, std::vector and std::ifstream keep their data private and offer public functions that protect invariants such as the size and capacity staying consistent. GUI toolkits model windows, buttons and text boxes as classes, and express "a Button is a Widget" with inheritance. Game engines commonly model entities, components and scenes as classes as well.

In business applications, domain objects such as Order, Customer and Invoice keep their rules inside themselves, for example an Order that refuses new items once it has been completed. C++ does not insist that everything be a class, though. Free functions, templates and the standard algorithms are just as important, and good C++ code uses a class where there is an invariant to protect and plain functions for the rest.

Common mistakes

Common mistakes

1. Leaving data with a rule public

If speed is a public int, any line can set it to -40 or beyond maxSpeed, and the class can no longer defend itself. Keep state private and let functions such as accelerate() be the only way to change it.

2. Writing a getter and a setter for every member

Offering both setSpeed(int) and speed() turns private data into public data in disguise, since anyone can still store any value. Tell a car accelerate(30) and brake(10), not "set your speed to 120": functions that describe an action can enforce the rules.

3. Using inheritance only to reuse code

Making Car inherit from Engine lets it call engine functions, but "a car is an engine" is false: a car has an engine. Make Engine a data member of Car. Use inheritance only when "X is a Y" is true and X can be used everywhere a Y is expected.

4. Forgetting const on a function that only reads

Without const on report(), it cannot be called through a const Car& parameter, so passing const references between functions starts to fail. Put const on every member function that does not change the object from the start.

Best practices

Best practices

  • Write each class's invariant as one sentence; if you cannot, you may not need a class yet.
  • Keep state private and expose member functions that describe actions.
  • Mark every member function that does not change the object const.
  • Express "has-a" with a data member and "is-a" with inheritance; when unsure, choose the data member.

Mini challenge

Mini challenge: a Battery class

Write a class for a chargeable battery. The class itself must guard the invariant that the charge always stays between 0 and 100 percent. Then create two objects and show that each keeps its own state.

  • Write a Battery(std::string label) constructor and private members label_ and percent_ (starting at 0)
  • void charge(int amount): ignore amount <= 0, and never let percent_ go above 100
  • bool use(int amount): return false and change nothing if amount is invalid or more than what is left; otherwise subtract it and return true
  • Write level() and label() as const functions, and print the phone and torch batteries with show()
battery.cpp
#include <iostream>
#include <string>
#include <utility>

class Battery {
public:
    // TODO: constructor taking a label
    // TODO: charge(int amount): ignore amount <= 0, cap the level at 100
    // TODO: bool use(int amount): refuse invalid or too-large amounts
    // TODO: level() and label() getters, both const

private:
    // TODO: label_ and percent_ (percent_ starts at 0)
};

void show(const Battery& b) {
    // TODO: print "<label>: <level>%"
}

int main() {
    // TODO: phone and torch batteries; charge phone by 80 then 50, torch by 30
    // TODO: show both, then try torch.use(50) and torch.use(20), show torch again
}

Expected: The output should be: phone: 100% torch: 30% torch use 50: false torch use 20: true torch: 10%

Show hint

In charge(), add first, then cap the result at 100. In use(), return false early when amount <= 0 || amount > percent_. show() takes a const Battery&, so level() and label() will not compile unless they are const. Use std::boolalpha to print a bool as true or false.

Show solution
battery.cpp
#include <iostream>
#include <string>
#include <utility>

class Battery {
public:
    explicit Battery(std::string label) : label_(std::move(label)) {}

    void charge(int amount) {
        if (amount <= 0) return;
        percent_ += amount;
        if (percent_ > 100) percent_ = 100;
    }

    bool use(int amount) {
        if (amount <= 0 || amount > percent_) return false;
        percent_ -= amount;
        return true;
    }

    int level() const { return percent_; }
    const std::string& label() const { return label_; }

private:
    std::string label_;
    int percent_ = 0;
};

void show(const Battery& b) {
    std::cout << b.label() << ": " << b.level() << "%\n";
}

int main() {
    Battery phone("phone");
    Battery torch("torch");

    phone.charge(80);
    phone.charge(50);
    torch.charge(30);
    show(phone);
    show(torch);

    std::cout << std::boolalpha;
    std::cout << "torch use 50: " << torch.use(50) << '\n';
    std::cout << "torch use 20: " << torch.use(20) << '\n';
    show(torch);
}

Quick quiz 1 / 3

class Counter has add(int n), total() and a private total_ = 0. What does Counter a; Counter b; a.add(5); b.add(2); a.add(1); std::cout << a.total() << ' ' << b.total(); print?

Quick quiz 2 / 3

class Car has a private speed_ and public accelerate() and report(). Which statement in main fails to compile?

Quick quiz 3 / 3

Which relationship is a good fit for inheritance rather than a data member?

What to remember

  • A class is the blueprint and an object is a real value built from it; every object has its own copy of the data members.
  • An invariant is a fact about the data that must always hold; private data and member functions protect it (encapsulation).
  • class and struct differ only in default access: class is private, struct is public.
  • Express "has-a" with a data member and only "is-a" with inheritance; polymorphism picks the function by the real object.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

OOP Intro | Thuta Learning