Should a member function that returns a static
member variable also be static
?
For instance:
struct T {
static int i;
static int getNumber() {
return i;
}
};
Should getNumber
be static
or not?
A static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class.
A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared. Suppose a static member function f() is a member of class X . The static member function f() cannot access the nonstatic members X or the nonstatic members of a base class of X .
It's not compulsory. you can write a member function that returns a static variable. You cannot go the other way around (write a static function which returns an instance variable).
A static variable declaration is only executed once, the first time the function is executed. A static variable is initialized only once (since this is part of the declaration process) and will be initialized to 0 unless the programmer designates otherwise.
Usually, yes.
If the variable doesn't have any per-instance state, then what possible per-instance logic could the function perform on it before returning it?
It's not compulsory. you can write a member function that returns a static variable. You cannot go the other way around (write a static function which returns an instance variable).
As an example of a case where you may want to return a static member, imagine a circumstance where the class holds a state variable and based on the state you would return one of the static values. Not that this is good design, but its not completely inconceivable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With