C++ Programming: Objects, RAII and the STL ยท Classes and Objects

this and static Members

this points to the object a method runs on; static members are shared by every object of the class.

this_static.cpp

#include <iostream>
using namespace std;

class Counter {
public:
    static int instances;       // one shared copy for the whole class
    int value;

    Counter(int value) {
        this->value = value;    // this-> is the object being built
        instances++;
    }

    Counter &add(int n) {
        value += n;
        return *this;           // return the object itself so calls can be chained
    }
};

int Counter::instances = 0;

int main() {
    Counter a(1);
    Counter b(5);
    a.add(2).add(3);
    cout << a.value << " " << b.value << " " << Counter::instances << endl;
    return 0;
}

Step by step

  1. C++ calls global, with Counter::instances = 0. It gets its own variables on the stack. C++ runs the Counter constructor to set up the new object, with value = 1.
  2. this->value is the field; plain value is the parameter.
  3. instances is static: one shared count.
  4. Counter() has finished, so its variables are gone. a is created on the stack with the value {instances: 1, value: 1}.
  5. C++ runs the Counter constructor to set up the new object, with value = 5.
  6. this->value is the field; plain value is the parameter.
  7. instances is static: one shared count.
  8. Counter() has finished, so its variables are gone. b is created on the stack with the value {instances: 2, value: 5}.
  9. C++ calls add(), with n = 2. It gets its own variables on the stack.
  10. a changes from {instances: 2, value: 1} to {instances: 2, value: 3}.
  11. return *this hands back the object itself, so another .add can follow.
  12. n changes from 2 to 3.
  13. a changes from {instances: 2, value: 3} to {instances: 2, value: 6}.
  14. The method returns *this.
  15. add() has finished, so its variables are gone.
  16. It prints 6 5 2.
  17. The method returns 0.
  18. 6 5 2.