The question Where should I put functions that are not related to a class has sp
ID: 652460 • Letter: T
Question
The question Where should I put functions that are not related to a class has sparked some debate over whether it makes sense in C++ to combine utility functions in a class or just have them exist as free functions in a namespace.
I come from a C# background where the latter option does not exist and thus naturally trend toward using static classes in the little C++ code I write. The highest voted answer on that question as well as several comments however say that free functions are to be preferred, even suggesting static classes were an anti-pattern. Why is that so in C++? At least on the surface, static methods on a class seem indistinguishable from free functions in a namespace. Why thus the preference for the latter?
Would things be different, if the collection of utility functions needed some shared data, e.g. a cache one could store in a private static field?
Explanation / Answer
I guess to answer that we should compare the intentions of both classes and namespaces. According to Wikipedia:
Class
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.