C++ Classes

Group data and behavior.

C++
#include <iostream>
class Counter { public: int value = 0; void increment() { value++; } };
int main() { Counter c; c.increment(); std::cout << c.value; }
Output
1

Explanation

A class defines a custom type. Public members are accessible to users of that type.

Explore the dry run
Guided walkthroughReady
1#include <iostream>
2class Counter { public: int value = 0; void increment() { value++; } };
3int main() { Counter c; c.increment(); std::cout << c.value; }

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Define Counter with an integer value and increment method.—
—
Create c with value 0, call increment, then print value.c.value = 1
1