the stackCup aCup bCup cfill Afill Bwash Bfill Cwash Cwash A1struct Cup {2 char id;3 Cup(char c) : id(c) {4 std::printf("fill %c\n", id);5 }6 ~Cup() {7 std::printf("wash %c\n", id);8 }9};1int main() {2 Cup a('A');3 {4 Cup b('B');5 }6 Cup c('C');7}ABC~
Violet cards: the code (the class Cup, and main)Blue slots: memory on the stack, solid while an object lives thereTokens: a lettered object (A, B, C) and the ~ that ends its lifeIn front: the class struct Cup, whose constructor prints fill and whose destructor prints wash, and main(), which creates three Cup objects. At the back: the stack, with a slot for each object, and the program's output. Creating an object sets its memory aside and runs the constructor; reaching the closing brace of its block runs the destructor and gives the memory back. At main's end, c is destroyed before a: objects in a block are destroyed in the reverse order of their construction. The figure gives each object its own slot on the stack. The real layout is up to the compiler, which may reuse b's memory for c once b is gone.

The class

  1. A constructor is a member function with the same name as its class and no return type. C++ calls it for you every time an object of the class is created. Its job: give the new object a valid starting state.

Lifetimes

Why it matters

What happens

;; step 1/9 · ctor
3    Cup(char c) : id(c) {        
4      std::printf("fill %c\n", id);
5    }                            

Cup(char c)   same name as the class, no return type
              takes a parameter c, like any function
runs          automatically, once, when a Cup is created
you never     call it by name: Cup a('A'); calls it

The two cards are one real file, cups.cpp, which starts with #include <cstdio> (for std::printf). Build it with g++ -std=c++20 -Wall -Wextra cups.cpp -o cups and run ./cups: it prints fill A, fill B, wash B, fill C, wash C, wash A. The figure gives each object its own slot on the stack. The real layout is up to the compiler, which may reuse b's memory for c once b is gone.