Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static member function? [duplicate]

Possible Duplicates:
Where would you use a friend function vs a static function?
C++: static member functions

When is it appropriate to use a static member function in C++? Please give me a real world example.

like image 235
Umesha MS Avatar asked Feb 07 '11 12:02

Umesha MS


1 Answers

Good uses of static member functions:

  • Meta-programming. Real-world example is template std::char_traits. All member functions are static
  • Making it a static member function gives it access to private members of the class, although a friend would suffice here too
  • A protected static member function thus is accessible only to the class and classes derived from it.

Note that the last case applies to a protected static member function but not a private one. In the latter case you would just put it into the compilation unit of the class, hiding it away as an implementation detail. For a protected one though you want it to be visible, albeit in a restricted way.

A typical case of that one is "cheating" the lack of inheritance of friendship.

class B
{
   friend class A;
   // lots of private stuff
};

class A
{
protected:
   static void callsSomePrivateMembers( B& b );
};

class AChild : public A
{
   void foo( B& b );
}

void AChild::foo( B& b )
{
      // AChild does not have private access to B as friendship is not inherited
      // but I do have access to protected members of A including the static ones

    callsSomePrivateMembers( b ); // get to call them through a back-door
}
like image 191
CashCow Avatar answered Oct 02 '22 20:10

CashCow