Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function returning a static variable

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?

like image 301
Itzik984 Avatar asked Sep 07 '11 18:09

Itzik984


People also ask

Can member functions access static variables?

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.

Can a member function be static?

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 .

Can a function return a static variable C++?

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).

Can you declare a static variable in a function?

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.


2 Answers

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?

like image 159
Lightness Races in Orbit Avatar answered Oct 12 '22 10:10

Lightness Races in Orbit


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

like image 40
Foo Bah Avatar answered Oct 12 '22 11:10

Foo Bah