Itzik984
Itzik984

Reputation: 16824

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?

Upvotes: 6

Views: 9850

Answers (2)

Foo Bah
Foo Bah

Reputation: 26281

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

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

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?

Upvotes: 8

Related Questions