Codiqo

Learn C++ · lesson 38 of 61 · about 8 minutes

Classes and Objects

Fill the arena with monsters: define a class with data members and member functions, and create objects from it.

What you'll learn

  • Define a class
  • Create objects
  • Call member functions

The arena

Below the castle there's an arena with a rat and a wolf. Both are monsters: each has a name and some health, and each can be hit and say how it's doing. Instead of two loose variables for every monster, the adventure gets a Monster class that bundles them, and the rat and the wolf are two objects made from it. Hitting the rat changes only the rat's health, because every object has its own copy of the data.

Blueprints for objects

A class bundles data (members) and the functions that work on it (member functions, or methods). Each object made from the class has its own copy of the data.

Members are private by default in a class, so you mark the ones the outside world may use as public.

A pet class

#include <iostream>
#include <string>

class Pet {
public:
    std::string name;
    int hunger = 5;

    void feed(int amount) {
        hunger -= amount;
        if (hunger < 0) hunger = 0;
    }

    void status() const {
        std::cout << name << ": hunger " << hunger << "\n";
    }
};

int main() {
    Pet a;
    a.name = "Phoebe";
    Pet b;
    b.name = "Rex";
    a.feed(2);
    b.feed(10);
    a.status();
    b.status();
}

Output

Phoebe: hunger 3
Rex: hunger 0

Tip

const after a member function (void status() const) promises it won't change the object. Mark every function that only reads like this.

Member functions use the members directly

Inside a member function, a member's name on its own means that member of the object the function was called on. So water -= litres; in drain() changes the water of whichever barrel you called it on, and the check after it keeps the value sensible.

A barrel that never goes below empty

#include <iostream>

class Barrel {
public:
    int water = 10;

    void drain(int litres) {
        water -= litres;
        if (water < 0) water = 0;
    }
};

int main() {
    Barrel b;
    b.drain(4);
    std::cout << b.water << "\n";
    b.drain(9);
    std::cout << b.water << "\n";
}

Output

6
0

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.