Archie Gertsman
Archie Gertsman

Reputation: 1661

C++ Static Function: Put Inside or Outside Scope of Class?

Say I have a class as follows in a header file:

class A {
public:
    void foo();
}

The function foo needs to call another "helper" function named bar. Bar isn't needed anywhere else other than inside foo. Should it be defined statically outside the scope of A:

(source file)

static void bar() { ... }
void A::foo() {
    bar(); ...
}

or within the class?

(header)

class A {
public:
    void foo();

private:
    void bar();
}

(souce)

void A::bar() { ... }
void A::foo() {
    bar(); ...
}

Upvotes: 0

Views: 2602

Answers (2)

rsjaffe
rsjaffe

Reputation: 5730

Generally, you should only allow access to the internals of a class when necessary. Placing the function outside the class and restricting its scope--either as a static function or within an anonymous namespace, would be best. That way, you're not polluting the global namespace and you're not allowing unnecessary access to class internals.

For example, you can, in the class's cpp file, have:

namespace {
   void bar() {.....}
}

and that helper function is then available for your class methods in the same cpp file.

Static functions in the cpp file would also have file scope only, but I find the static keyword to be confusing when used that way.

Upvotes: 2

tdao
tdao

Reputation: 17668

Bar isn't needed anywhere else other than inside foo.

If so then bar should be a private member function of class A - there is no need to define bar in global namespace.

static void bar() { ... }  // not needed

instead use:

void A::bar() { ... } // <- bar should be private member function

Upvotes: 3

Related Questions