Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function vs Static member functions C++ [duplicate]

I've been reading a bit about static functions and static member functions. From my understanding if a function is declared static then this function is only visible to it's translation unit and nowhere else. A static member function instead is a function that can be called without instantiating any object of its class (so you can use it like it was in a name space).

To clarify with static function I mean something like

static int foo(int a, int b)
{
   return a + b;
}

And with static member function I mean

struct MyClass
{
   static int foo(int a, int b)
   {
      return a + b;
   } 
}

Is this the only difference? or is the visibility within the same translation unit still a common feature for the two of them?

like image 636
user8469759 Avatar asked Jul 22 '26 04:07

user8469759


1 Answers

As you can see on this page, static actually has 3 different meanings depending on where it's used.

  1. If it's used inside a block scope, like inside a function, then it'll make a variable persist across function calls.
  2. If a class method is declared as static, then it's not bound to a specific instance of the class.
  3. If a namespace member is declared as static, then it has internal linkage only.
like image 79
Aplet123 Avatar answered Jul 24 '26 19:07

Aplet123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!