3

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?

user8469759
  • 2,522
  • 6
  • 26
  • 50
  • Are you only asking about internal/externable linkage or are you looking for all differences? E.g., a static member function can be called using the dot operator on an instance of the class, while a static nonmember function cannot. – AndyG Apr 20 '20 at 12:01
  • @AndyG, nothing about syntax. Mainly about linkage. – user8469759 Apr 20 '20 at 12:01
  • A static member function is still a member function, it just doesn't need an object to be called on (which means it has no `this` pointer). It can be seen as a class-function instead of an object-function, and is available for all translation units which have the declaration of it. A static non-member (also called namespace-scope) function have static [storage duration](https://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration) and internal [linkage](https://en.cppreference.com/w/cpp/language/storage_duration#Linkage). – Some programmer dude Apr 20 '20 at 12:02
  • 2
    `static` is one of the keywords with different meanings depending on context. Don't get confused by the same keyword being used for different things (https://en.cppreference.com/w/cpp/keyword/static) – 463035818_is_not_an_ai Apr 20 '20 at 12:02
  • @user8469759: Then it seems you understand it well enough already. Just bear in mind that in gcc symbols are exported by default but in MSVC we need to explicitly export/import them with the `__declspec` directive. So even for a static member function, it may not be visible outside its translation unit in Windows unless you make it so. – AndyG Apr 20 '20 at 12:06
  • Why was the question closed? The other question asks when to use friend vs static member function... – user8469759 Sep 03 '23 at 02:49

1 Answers1

7

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.
smailzhu
  • 3
  • 2
Aplet123
  • 33,825
  • 1
  • 29
  • 55