C++ Programming: Objects, RAII and the STL ยท Classes and Objects
this points to the object a method runs on; static members are shared by every object of the class.
#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;
}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.Counter() has finished, so its variables are gone. a is created on the stack with the value {instances: 1, value: 1}.Counter constructor to set up the new object, with value = 5.Counter() has finished, so its variables are gone. b is created on the stack with the value {instances: 2, value: 5}.add(), with n = 2. It gets its own variables on the stack.a changes from {instances: 2, value: 1} to {instances: 2, value: 3}.n changes from 2 to 3.a changes from {instances: 2, value: 3} to {instances: 2, value: 6}.*this.add() has finished, so its variables are gone.6 5 2.0.