← C++ from Scratch Lesson 37 of 62 · 10 XP

Class methods

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Methods are functions inside a class. They see the object's fields directly:

class Hero {
public:
    std::string name;
    int hp = 100;

    void takeDamage(int d)
    {
        hp -= d;
        if (hp < 0) hp = 0;
    }

    bool alive() const      // const — the method promises not to change the object
    {
        return hp > 0;
    }
};

Hero h;
h.takeDamage(30);           // a call with a dot: the method works with h's fields

Long methods are often written outside the class: inside it there's the declaration void takeDamage(int d);, and outside it, void Hero::takeDamage(int d) { … }. Hero:: says whose method it is.

Task. A class Counter with the methods add(int), reset() and int value() const. Read commands until the end of the input: add N, reset, print (print the value). Carry them out.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.