0

Why we have to declare static member function to access private static variable? Why not simply use a public function to access s_nValue? I mean why is it better to use static member function instead of a non-static public function?

class Something { private: static int s_nValue; }; int Something::s_nValue = 1; // initializer int main() { } 
5
  • 2
    Of course you can use a public member function to access (get or set) static member variables, even if the static member variable is private. Commented Aug 9, 2013 at 6:56
  • 1
    The question is not clear! Commented Aug 9, 2013 at 6:56
  • @Nawaz I read it on learncpp.com that its better to use static member function. I want to know is there any problem with a normal get_Value public function? Am I clear now? Commented Aug 9, 2013 at 6:58
  • @Jigyasa As I wrote in my answer, the "problem" is that you need an instance of the class if the method is non-static. If it's static you can just do TypeName::Methodname(); Commented Aug 9, 2013 at 7:04
  • @Borgleader: I prefer to not use private static members in header files. I do not want them cluttered. Instead I put them .cpp file with internal linkage. Commented Aug 9, 2013 at 7:09

3 Answers 3

5

Why we have to declare static member function to access private static variable?

You don't have to:

class Something { private: static int s_nValue; public: static int staticAccess() { return s_nValue; } int Access() { return s_nValue; } }; int Something::s_nValue = 1; // initializer int main() { Something s; Something::staticAccess(); s.Access(); return 0; } 

Both methods work as can bee seen here

That being said, it doesn't really make sense to make a non-static member function to access a static variable (as you would need an instance of the class to be able to call it).

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

Comments

2

If you use pubilc function , you have to call it using an object, and it's not appropriate to call a static function with object, so better to keep it in static method which can be accessible directly through "classname::"

Comments

1

Why we have to declare static member function to access private static variable?

You don't have to. You can access a private static member from any member function, static or otherwise. You can also access it from any friend function, or member function of a friend class.

Why not simply use a public function to access s_nValue?

Because that's less simple than a static function. You need an object to call a non-static member function; why not simply allow access to the static variable without creating an object?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.