C/C++ Arena

Step 1 of 9

Member functions

In C, a struct holds data, and separate functions operate on it: void take_damage(struct Player *p, int d). C++ lets you put those functions inside the struct, as member functions (also called methods). Data and the operations on it live together.

#include <iostream>

struct Counter {
    int value = 0;
    int step = 1;

    void increment() { value += step; }
    void reset() { value = 0; }
    bool over(int limit) { return value > limit; }
};

int main() {
    Counter c;
    c.step = 5;
    c.increment();
    c.increment();
    std::cout << c.value << " " << c.over(8) << "\n";
    c.reset();
    std::cout << c.value << "\n";
}
10 1
0

What's new

How it works underneath

A member function is compiled like a normal function with a hidden extra parameter: a pointer to the object, called this. c.increment() is roughly increment(&c), and value inside means this->value. The Watch it run example for classes shows this pointing back at the object.

Your turn: complete the member function reload so it refills ammo to mag_size.

Next: public and private