Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static functions acceptable practice for certain things in c++?

Tags:

c++

Sometimes, for certain things like writing a line to a console, feels like something that should be globally accessible to all objects. Something like:

writeError("UNHANDLED EXCEPTION",someData);

Also things such as math functions feel this way too. But how do you draw the line when doing this sort of thing becomes bad practice?

like image 260
jmasterx Avatar asked Dec 04 '22 08:12

jmasterx


2 Answers

Some people draw the line at the point where the non-member function needs to be a friend of one of its arguments, so they use a lot of free functions.

Some people draw the line at the point where the non-member function could reasonably be a member function of one of its arguments, even though it doesn't actually use the class internals. They have somewhat fewer free functions.

It's usually best not to think of this as "becoming bad practice" - not all design in C++ is "properly" object-oriented. If your task is best solved by means other than OOP, then using OOP is itself "bad practice". The argument how best to design your code can go on indefinitely in any language, but C++ doesn't make any particular effort to steer you towards writing classes.

See also:

Effective C++ Item 23 Prefer non-member non-friend functions to member functions

like image 50
Steve Jessop Avatar answered May 20 '23 05:05

Steve Jessop


Global APIs of this nature are just fine.

The best practice these days being to wrap them in a namespace:

namespace LOGGING { 
     void writeError(message, ...); 
} 

Making something static in C++ is not the same thing as making something static in Java. In C++, a static function is only visible from that compilation unit (.cpp file). It does not make it a global non-class function.

A static member function in C++ however, is the same in Java - it allows it to be called from outside of an object context class::method(params) instead of classObject.method(params).

like image 25
Chris K Avatar answered May 20 '23 07:05

Chris K