Jigyasa
Jigyasa

Reputation: 186

Private static variable

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()
{

}

Upvotes: 0

Views: 993

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254461

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?

Upvotes: 1

Raju
Raju

Reputation: 1169

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::"

Upvotes: 2

Borgleader
Borgleader

Reputation: 15916

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

Upvotes: 5

Related Questions