Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private vs. Static functions in C++

Tags:

Is there any advantage to using private (probably also static) functions in a class for utility functions used in my class that do not need access to an instance's data over using global static functions in my .cpp file that implements the class?
The first sounds cleaner to me, but the second really makes more sense as these functions do not need to even be mentioned in the .h file.

like image 318
Baruch Avatar asked Jul 27 '11 09:07

Baruch


People also ask

What is the difference between static function and normal function in C?

Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.

What is a static function in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

Can private functions be static?

Yes, we can have private methods or private static methods in an interface in Java 9.

What is a static function?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.


1 Answers

I would not put private static functions to the header file if they are not needed. They would just pollute the header file and add more work.

But private static functions may be needed when you have a template method/function in a class and want to use that helper function in it.

Another reason for using private static functions instead of global static functions is that they can access private class members (variables, functions).

like image 106
Juraj Blaho Avatar answered Sep 18 '22 23:09

Juraj Blaho