Question

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?

Was it helpful?

Solution

  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

OTHER TIPS

I suggest you try and split your reasoning between interface and implementation. If you need to call your setter/getter when no instance of the class has been instantiated, make them static. If you may need to override them make them non static and virtual.

I'm assuming you do need them both; this would be the case if your static data member is private only because you need to ensure its value meets some criteria. If it is involved in more complex logic you might want to reconsider your interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top