2

Is it still worth using static functions in C++ as a helpers?

Example: in file.cpp

static void helperFunc() { do something }

// class implementation
// ...

// some public method, not static
void myClass::doSomething() { helperFunc(); }

That way I do not have to declare private method in class's declaration.

Or maybe it is better to use unnamed namespaces and write (in the same file as above)?

namespace {
    void helperFunc() { }
}

What is better?

fen
  • 9,835
  • 5
  • 34
  • 57
  • Is `myClass::doSomething()` static as well? – Luchian Grigore Jan 18 '13 at 09:14
  • 2
    http://stackoverflow.com/a/3070815/1467309 this answers for your question – acrilige Jan 18 '13 at 09:15
  • Why you don't want to declare a private method ? – log0 Jan 18 '13 at 09:20
  • helperFunc can often change and when it is in header file (as a private method) it involves whole project rebuild. Having this as a static function is more "local" and easier to change – fen Jan 18 '13 at 09:22
  • @fen I don't get it. You don't have to put the private method definition in the header. And in fact in your example you indeed put the method definition in the source file – log0 Jan 18 '13 at 09:26
  • 1
    For the difference between using static and anonymous namespace for this purpose, check http://stackoverflow.com/questions/154469/unnamed-anonymous-namespaces-vs-static-functions – Sander De Dycker Jan 18 '13 at 09:33

2 Answers2

2

Neither of your two examples is better than the other. It's a matter of style. The static keyword is more expressive. It outright spells out "do not export this name". Using an anonymous namespace is not that expressive. The fact that the name won't get exported is a side-effect, not a primary function.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
-3

It's better to declare a private (possibly static) method in the class.

user1610015
  • 6,561
  • 2
  • 15
  • 18
  • For the same reason that methods in general are better than global functions. All global functions are unrelated to each other because they don't belong to any class and so they are confusing. Why do you think Java and C# don't allow global functions? – user1610015 Jan 18 '13 at 09:28
  • It's not better nor worse. It depends on what the function is doing. – Nikos C. Jan 18 '13 at 09:30
  • 2
    @user1610015 C++ is not Java and it's not C#. – Nikos C. Jan 18 '13 at 09:30
  • 1
    @user1610015 you do know what a C++ namespace is? `static` methods are about as related to each other as functions in a namespace. – Luchian Grigore Jan 18 '13 at 09:33
  • @LuchianGrigore No they're not because a namespace can contain several classes, but not viceversa. A class groups members tighter than a namespace does. – user1610015 Jan 18 '13 at 09:46