7

I was inspired by the comments under this question.

I didn't see any reason why a class with only static functions would be a better design than a namespace (with just functions). Any list of pros and cons of these two approaches are welcomed. It would be great with some practical examples!

8
  • 1
    A class with only static member functions would be familiar to Java programmers, and would encourage them to write C++ code as if it was Java. Commented Apr 19, 2013 at 15:58
  • Isn't the preferred way in C++ to use the namespace way? Commented Apr 19, 2013 at 15:58
  • @PeteBecker what if I only make friends with C++ developers? Lol Commented Apr 19, 2013 at 15:59
  • 1
    @PeteBecker Is that a pro or a con argument? ;) Commented Apr 19, 2013 at 15:59
  • 1
    @DanielFrey it is only a pro if you really really like the sight of new. Commented Apr 19, 2013 at 16:01

2 Answers 2

11

One non-stylistic difference is that you can use a class as a template parameter, but you cannot use a namespace. This is sometimes used for policy classes, like std::char_traits.

Outside of that use case, I would stick to a namespace with regular functions.

Sign up to request clarification or add additional context in comments.

5 Comments

Throw in access specifiers as a difference, perhaps?
@Drew what for? In a class with only static methods, there is nothing to encapsulate, by definition.
public static methods implemented in terms of private ones that shouldn't be accessed directly.
@DrewDormann you can define whose private static methods in the .cpp file without declaring them in .h file in the namespace approach
@user2207811 In the (likely) case that any function is needed in only one translation unit, yes.
3

Classes with static methods

  • You can have class inside another class, you can't have namespace inside class (because it probably does not make any sense).
  • They work with very ancient compilers.

Namespaces

- you can create namespace aliases

namespace io = boost::iostreams; Well, you can typedef classes, so this is moot point.

  • you can import symbols to another namespaces.

    namespace mystuff { using namespace boost; }

  • you can import selected symbols.

    using std::string;

  • they can span over several files (very important advantage)

  • inline namespaces (C++11)

Bottom line: namespaces are way to go in C++.

2 Comments

Actually, namespace inside classes make a lot of sense.
It would be good to explain why "they can span over several files" is an important advantage.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.