1

What's the difference between these two declarations?

class foo
{
public:
    static void bar();
};

and

namespace foo
{
    void bar();
}

The way I see it, there is none, since bar in class foo doesn't have access to this, and neither does bar in namespace foo.

This is purely theoretical, of course.

Daniel Kamil Kozar
  • 18,476
  • 5
  • 50
  • 64
  • I'm not a C++ expert, but I would say that the main difference is that you can create instances of class foo, but not of the namespace. (Of course creating instances of a class that only has one static member is rather useless...) EDIT: Oh, and you might also inherit from class foo, in that case it might even make sense to have an almost empty class like that. – ValarDohaeris Apr 27 '13 at 13:06
  • @ValarDohaeris: You can prevent this to a certain extent by making the destructor or constructor private. – Alexandre C. Apr 27 '13 at 13:24
  • possible duplicate of [Namespace + functions versus static methods on a class](http://stackoverflow.com/questions/1434937/namespace-functions-versus-static-methods-on-a-class) – Kate Gregory Apr 27 '13 at 13:48
  • Also, check this link for a list of some differences: http://stackoverflow.com/a/3188198/908336 (The most important one is that you can reopen a namespace and add stuff across translation units, which is impossible with classes) – Masood Khaari May 21 '13 at 11:04

2 Answers2

7

What's the difference between a public static class member function and a global function declared in a namespace?

  • The class member function will be able to access private static member of the class, while a function inside a namespace will not directly have any kind of data protection
  • As pointed out by @ValarDohaeris, you can create an object of class foo and call obj.bar() even in an object context, while the same cannot be achieved with namespaces as there are no instances of namespaces
  • The namespace can be imported via using making bar() a valid call
  • As mentioned by @John5342 you can use the class foo at template argument. For example in template<typename T> fun() { T::bar(); }
Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272
7

Functions defined at namespace scope can be found via argument dependent lookup:

namespace foo
{
    class bar;
    void baz (bar);
}

foo::bar x;
baz (x); // Ok, baz is found by ADL

If foo is a class instead of a namespace, this does not work.

Alexandre C.
  • 55,948
  • 11
  • 128
  • 197
  • 2
    +1. Not the only difference but certainly an important one that is not mentioned in the answer accepted by the author of this question. – Aleph Apr 27 '13 at 13:26