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?

  • Sounds a bit like the "functional decomposition" antipattern. – user281377 Feb 11 '12 at 12:18
  • 10
    Short answer: You just don't need a class to wrap these functions. Free functions are a much cleaner fit for your task than crunching them into some pseudo-OO construct, which is a workaround you only need in "purely-OO" languages. – Chris says Reinstate Monica Feb 11 '12 at 16:02

I guess to answer that we should compare the intentions of both classes and namespaces. According to Wikipedia:


In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior. Data field members (member variables or instance variables) enable a class object to maintain state. Other kinds of members, especially methods, enable a class object's behavior. Class instances are of the type of the associated class.


In general, a namespace is a container that provides context for the identifiers (names, or technical terms, or words) it holds, and allows the disambiguation of homonym identifiers residing in different namespaces.

Now, what are you trying to achieve by putting the functions in a class (statically) or a namespace? I would wager that the definition of a namespace better describes your intention - all you want is a container for your functions. You don't need any of the features described in the class definition. Note that the first words of the class definition are "In object-oriented programming", yet there is nothing object-oriented about a collection of functions.

There are probably technical reasons as well but as someone coming from Java and trying to get my head around the multi-paradigm language that is C++, the most obvious answer to me is: Because we don't need OO to achieve this.

  • 1
    +1 for "we don't need OO to achieve this" – Ixrec Jan 5 '15 at 21:37
  • I agree with this as a no-fan of OO, but I guess that there are some fews situations where using an All-static class is the only solution, by example, replacing a namespace, since you can't declare a nested namespace inside a class. – Wael Boutglay Apr 1 '18 at 20:35

I'd be very cautious in calling that an anti-pattern. Namespaces are usually prefered, but as there is no namespace templates and namespaces can't be passed as template parameters, using classes with nothing but static members is quite common.

  • 3
    The other answers have glossed over the last line of the OP. Namespaces are pretty much named scopes, so if you need access control, classes are the only tool available. – cmannett85 Feb 11 '12 at 11:43
  • 2
    @cbamber85 to be fair, I had put that line in only after reading the first two answers. – PersonalNexus Feb 11 '12 at 12:49
  • @PersonalNexus Ah fair enough, I didn't realise! – cmannett85 Feb 11 '12 at 12:51
  • 10
    @cbamber85: That is not entirely true. You'd get even better encapsulation by putting "private" functions in the implementation file, so the users don't get to see even the private declaration. – UncleBens Feb 11 '12 at 13:21
  • 3
    +1 Templates are indeed a point where namespaces still lack features. – Chris says Reinstate Monica Feb 11 '12 at 16:05

Back in the day I needed to take a FORTRAN class. I knew other imperative languages by then, so I figured I could do FORTRAN without much studying. When I turned in my first homework, professor returned it to me and asked to redo it: he said that Pascal programs written in FORTRAN syntax do not count as valid submissions.

Similar issue is in play here: using static classes to host utility functions in C++ is a foreign idiome to C++.

As you mentioned in your question, using static classes for utility functions in C# is a matter of necessity: free-standing functions are simply not an option in C#. The language needed to develop a pattern for allowing programmers define free-standing functions in some other way - namely, within static utility classes. This was a Java trick taken word-for-word: for example, java.lang.Math and System.Math of .NET are nearly isomorphic.

C++, however, offers namespaces, a different facility for achieving the same goal, and it actively uses it in the implementation of its standard library. Adding an extra layer of static classes is not only unnecessary, but also somewhat counterintuitive to readers without C# or Java background. In a sense, you are introducing a "loan translation" into the language for something that can be expressed natively.

When your functions need to share data, the situation is different. Because your functions are no longer unrelated, Singleton pattern becomes the preferred way of addressing this requirement.

  • 7
    +1, except for recommending singletons. They are not preferred in C++! Functions may be in a class if they need to share state, but classes should not be singletons unless they really, really need to be. And they usually don't. – Maxpm Feb 11 '12 at 18:50
  • @Maxpm Don't get me wrong, singleton is preferred only to global static variables. Other than that, there is nothing "preferred" about that. – dasblinkenlight Feb 11 '12 at 19:47
  • 2
    There is this good article, Singletons: Solving Problems You Didn't Know You Never Had Since 1995. Summarized it says that coupling the well known instance to the class itself unnecessarily limits your flexibility and gives you nothing. Most of the time just have a class and have a shared instance somewhere, but don't make it singleton. – Jan Hudec Feb 17 '12 at 9:00
  • I'm not sure "foreign idiom" is the right term. It's a very common idiom. I think quite a few programming teams are using e2 of Stroustrup... – Nick Keighley May 25 '17 at 11:10

Perhaps you need to ask why you would want an all-static class?

The only reason I can think of is that other languages (Java and C#) that are very much 'everything is a class' require them. These languages cannot create top-level functions at all, so they invented a trick to keep them, and that was the static member function. They're a bit of a workaround, but C++ doesn't need such a thing, you can create brand new top-level, independent functions directly.

If you need functions that operate on a specific data item, then it makes sense to bundle them into a class that holds the data, but then, these stop being functions and start being members of that class that operate on the class' data.

If you have a function that doesn't operate on a particular data type (I use the word here as classes are ways to define new data types) then it really is an anti-pattern to shove them into a class, for no other than semantic purposes.

  • 10
    Indeed - I would say that the "class with all static members" in Java is actually a hack to get around a limitation of Java. – Charles Salvia Feb 11 '12 at 15:03
  • @CharlesSalvia: I was being polite :) I have the same bad feeling about main() being part of a java class too, though I understand why they did that. – gbjbaanb Feb 12 '12 at 13:39
  • This actually seems to provide the answer to why you'd want an all-static class. Or do I misunderstand you? For example, I need to hold a variable whose value can change that is read by one class (which I intend to store in ROM) and written to by another class (which will be in RAM). Simply placing the at a known ram location is not sufficient - wrapping it (and it's accessors) in a class allows me to fine tune access control. Pretty much what you describe in your second paragraph. – iheanyi Jun 12 '14 at 14:52

At least on the surface, static methods on a class seem indistinguishable from free functions in a namespace.

In other words having a class instead of a namespace has no advantages.

Why thus the preference for the latter?

For one thing it saves you typing static all the time, though that's arguably a rather minor benefit.

The main benefit is that it's the least powerful tool for the job. Classes can be used to create objects, they can be used as the type of variables or as template arguments. Neither of those are features you want for your collection of functions. So it's preferable to use a tool that doesn't have those features, so that the class can't accidentally be misused.

Following from that using a namespace makes it also immediately clear to any users of your code that this is a collection of functions and not a blueprint to create objects from.


... 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?

An all-static class will get the job done, but it's like driving a 53-foot semi truck to the grocery store for chips and salsa when a four-door sedan will do (i.e., it's overkill). Classes come with a small amount of additional overhead and their existence might give someone the impression that instantiating one might be a good idea. The free functions offered by C++ (and C, where all functions are free) don't do that; they're just functions and nothing else.

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?

Not really. The original purpose of static in C (and later C++) was to offer persistent storage that's usable at any level of scope:

int counter() {
    static int value = 0;

You can take the scope out to the level of a file, which makes it visible to all narrower scopes but not outside the file:

static int value = 0;

int up() { value++; }
int down() { value--; }

A private static class member in C++ serves the same purpose but is limited to the scope of a class. The technique used in the counter() example above also works inside C++ methods and is something I'd actually recommend doing if the variable doesn't need to be visible to the entire class.

  • I suppose a group of unrelated utility functions which share no data should be better grouped in a namespace. But if you have a group of tightly coupled utility functions that need access to shared data and perhaps some access control, a static class is the best choice. A static within a function is not reentrant. Using a module global... slightly better in this context, but I still think an all static class is the best solution if you have the requirements I described. – iheanyi Jun 12 '14 at 14:56
  • If they share data might they be better as a class without static methods? – Nick Keighley May 25 '17 at 11:23
  • @NickKeighley That depends on who wins the debate over whether it's better to create one instance and pass it around to everything that needs it or just make it static-in-class. – Blrfl May 25 '17 at 15:20

If a function maintains no state and is reentrant, there doesn't seem to be much point in shoving it inside a class, (unless forced to by the language). If the function maintains some state, (eg. it can only be made thread-safe by means of a static mutex), then static methods on a class seem appropriate.


Much of the discourse on the topic here makes sense, though there is something very fundamental about C++ that makes namespaces and classes/structs very different.

Static classes (classes where all members are static, and the class will never be instantiated) are themselves objects. They are not simply a namespace to contain functions.

Template meta-programming allows us to use a static class as a compile-time object.

Consider this:

template<typename allocator_type> class allocator
    inline static void* allocate(size_t size)
        return allocator_type::template allocate(size);
    inline static void release(void* p)
        allocator_type::template release(p);

To use it we need functions contained inside a class. A namespace will not work here. Consider:

class mallocator
    inline static void* allocate(size_t size)
        return std::malloc(size);
    inline static void release(void* p)
        return std::free(p);

Now to use it:

using my_allocator = allocator<mallocator>;

void* p = my_allocator::allocate(1024);

So long as a new allocator exposes an allocate and release function that is compatible, switching to a new allocator is easy.

This can not be achieved with namespaces.

Do you always need functions to be part of a class? No.

Is using a static class an anti-pattern? It depends on the context.

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?

In that case what you're trying to achieve is likely to be best served through object-oriented programming.


As John Carmack famously said:

"Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function."

I think that pretty much sums it up. Why would you make it forcefully a class if it's clearly not a class? C++ has the luxury that you can actually use functions; in Java, everything is a method. Then you need utility classes, and lots of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.