6

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?

2 Answers 2

8

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?

Sign up to request clarification or add additional context in comments.

2 Comments

@Ben, I was thinking of something else at the time I made the comment (i.e. hokey way of keeping track of count of instances)... anyways - removed the dodgy comment...
@Nim: I was wondering whether someone might bring up something like that. You're not going mad. But it's highly unlikely that you'd ever want to do that in a simple getter.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.