Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static or nonstatic getters/setters for static class variable in C++

Suppose I have the following class:

class A {
private:
    static double X;
};

double A::X = 0.0;

The variable A::X really ought to be static, because all instances of A must, in the context I'm concerned with, share the same value of A::X.

Now, my question is whether to make getter and setter functions for A::X static. They will be defined like this:

void A::setValue(const double x) {
#pragma omp critical
{
    if(x<0.0||x>1.0)
        // custom macro call to raise exception

    X = x;
}
}

double A::getValue() {
#pragma omp critical
{
    return X;
}
}

It seems to me that it makes absolutely no practical difference whether I add these getter and setter functions to A as static or as nonstatic member functions. Is this right?

In this example, or more generally, what reasons might there be to prefer that such getter and setter functions be made static or nonstatic members of the class whose static member they control access to?

like image 908
synaptik Avatar asked Mar 22 '23 03:03

synaptik


1 Answers

  1. you can call static methods if no object have been declared
  2. Your code is more readable: if you have a static method getA, you know that A is static
like image 95
Gabriel Avatar answered Mar 23 '23 17:03

Gabriel