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
- Default member values:
int value = 0;gives every newCountera starting value, so no object starts with garbage. - Member functions are declared inside the struct. Inside them, members are used directly by name:
value += stepmeans "this object'svalue". - You call them with a dot:
c.increment(). Each object has its own data, and the member function works on the object it was called on. - In C++ you write just
Counter c;; the wordstructisn't needed when you use the type.
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.