c++static-variables

How to make increment/decrement static variable for an API?


#include <iostream>

class Test {
public:
    static int numelem;
    Test() {}
    ~Test() {}
    int increment();
};

int Test::numelem = 0;

int Test::increment()
{
  return ++Test::numelem;
}

So I want to make a counter for my Stacks data structure. Whenever I push, it increments and when popped it decrements.

My code works, but int Test::numelem = 0; is a global variable. I tried using inline but unfortunately I have C++14.

I only put the static int numelem instead of the whole Stack class to focus on one feature.

Is there an alternative way I can put int Test::numelem = 0; inside the class without getting any error?


Solution

  • but int Test::numelem = 0; is a global variable.

    Technically, it is not a global variable but a class static member. Functionally they behave very similarly.


    Is there an alternative way I can put int Test::numelem = 0; inside the class without getting any error? unfortunately I have C++14.

    With C++14 the out-of-class definition for a nonconst static data member should be in the same namespace scope where the class was defined(global namespace in your example). So there is no way of defining a nonconst static data member inside the class in c++14 as we can't use inline in c++14 and the only way of defining a nonconst static data member is to put a definition at namespace scope.

    This can be seen from class.static.data:

    The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member's class definition.


    But with C++17 we can use inline to define a non-const static data member inside the class.