here’s the snippet in java:
class C {
private static int c = 0;
C(){ c++; }
public static int getC () { return c; }
}
public class TestC {
public static void main (...) {
C c1 = new C();
C c2 = new C();
// at this point C.getC() returns 2(int)
}
}
now I want to do something similar in C++, I have a basic understanding of class writing,
what should be the shortest snippet of code to implement the counter ?
here’s my example class:
class C {
public:
private:
}
int main () {
C c1;
C c2;
// printing the counter like C.getC();
}
Very similar.
In relevant header:
In one
.cppfile:It’s crucial to provide the definition of c in exactly one place (i.e. not in a header) or you will get linking errors.