When should we use non-member functions (or free functions) or static member functions? As far as I know, in Java or C# we use static member funtions in such cases when in C++ we could use free functions. But what is the practial usage difference?
-
"_As far as I know, in Java or C# we use static member funtions_" - because both Java, and C# don't have non-member functions. – Algirdas Preidžius Oct 30 '20 at 13:16
-
Some functions can't be meaningfully attributed to a type. Generic algorithms are a good example. – François Andrieux Oct 30 '20 at 13:21
2 Answers
In Java or C# you have to use static member functions because there is no way to write functions which are not part of a class.
In C++, you have that choice. There's little practical difference, so the decision is about code structure. Does the function you want to write seem to belong to a class, but not to a specific instance of that class? Then you might want a static member function. Does it need access to private static data in the class? Then you definitely need a member function!
Otherwise, it can be a free function in an appropriate namespace. And indeed should be, because there's no reason to make a class when a namespace will do.

- 9,809
- 3
- 27
- 36
-
I believe in C# you can write functions outside of class. They just have to be a part of a namespace. No? Not sure about Java but I guess it should be similar. – ALX23z Oct 30 '20 at 13:25
-
@ALX23z no you can't. There's a forthcoming language feature to allow you to do something that looks like that but it's only syntactic sugar for defining the entry point method for a program. And you can't do it in Java either. – Matthew Walton Oct 30 '20 at 13:26
The main difference is that static functions have access to private/protected members/methods of the class. Also, IDE can find static functions as members/methods to the class and it will be easier to code.
Only restriction is that you have to declare static functions with the class while free functions can be declared freely.

- 4,456
- 1
- 11
- 18