A visitor counter has both a number and an action: record another arrival. A class lets you describe those together. Like a struct, it defines a type from which you can create objects. Each object has its own non-static data members. A member function works with the object it is called on: tick() updates that object's counter, while read() only reports it. Neither operation changes every object of the class.
The class body ends with };, including the semicolon. Inside it, private: marks details that outside code cannot access directly. public: marks operations that other code may call. These labels apply until another access label appears. Classes are private by default; structs are public by default. Both can have data and functions.
A member function is written much like a function you already know, but inside the class it can use that object's member names directly. The dot in meter.tick() selects an operation on meter. Its empty parentheses mean this call supplies no arguments.
#include <iostream>
class Meter {
private:
int ticks = 4;
public:
void tick() { ticks += 1; }
int read() { return ticks; }
};
int main() {
Meter meter;
meter.tick();
std::cout << meter.read() << '\n';
}
The example prints 5. Unlike the public record fields in the previous section, ticks cannot be assigned directly from main; callers use the public functions. In the editor, start with count(), even though arrive() appears above it. Returning the stored count lets the untouched evening counter report zero. Then implement arrive() and watch the morning count change while the evening count stays the same.
count() return the stored visitors value. The untouched evening counter should report Evening: 0.arrive() increase visitors by one. The two supplied calls should produce Morning: 2.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.