Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we only use 'static' inside a class or a function (C++)?

I was recently reading Stroustrups The C++ Programming Language and in the section about Linkage in chapter 9 I came across the following paragraph:

"In C and older C++ programs, the keyword static is (confusingly) used to mean "use internal linkage". Don't use static except inside functions and classes."

The problem is that reading further on, the author did not elaborate on why this is bad practice. I use static functions from time to time in my code usually for some simple calculation that is not needed outside the compilation unit, but I never realised this was frowned upon and it is not obvious to me why it is bad. Can anyone shed light on this for me please??

like image 609
mathematician1975 Avatar asked Jul 02 '12 17:07

mathematician1975


People also ask

Why do we use static 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 the reason for using static members in class?

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.

Why do we need static member function?

The static member functions are special functions used to access the static data members or other static member functions. A member function is defined using the static keyword. A static member function shares the single copy of the member function to any number of the class' objects.


1 Answers

I think that the idea is not to frown upon internal linkage, but to avoid confusion with the new meaning of static: static has way too many meanings (declaring stuff with internal linkage, defining local variables with static storage duration, marking non-instance members of classes), so avoiding one of the less intuitive ones is a good thing.

Because of this, the C++98 standard provides another way to declare stuff with internal linkage: unnamed namespaces, and deprecates static "when declaring objects in a namespace scope".

The C++11 standard removed this deprecation (and also changed somehow the semantic of unnamed namespaces, not really requiring internal linkage), so it's now really a matter of style.

like image 80
Matteo Italia Avatar answered Nov 15 '22 00:11

Matteo Italia