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

Time:11-06

#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?

CodePudding user response:

This is the typical workaround. It's particularly useful for templates.

class Test {
public:
    static int& numelem() {
        static int val = 0; // or your initializer here
        return val;
    }

    int increment() {
        return   numelem();
    }
};

Of course, now you're accessing it with the syntax Test::numelem() instead of just Test::numelem. But something like Test::numelem() still works just fine.

CodePudding user response:

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.

  • Related