1

I know that namespace are preferred in C++ if you want to define static functions, but what to do when you have functions which access other functions but the other functions should be private and not be accessible by others. How to declare/define it ? Wouldn't it be much simple to use classes ? Or do I have to still use namespaces ?

Like this:

class Test1
{
public:
    static void Start()
    {
        if(1) // Some checks...
        {
            ProcessStart();
        }
    }

private:
    static void ProcessStart()
    {
        if(!Initialized)
        {
            //Initialize
        }

        // Do other stuff
    }

    static bool Initialized;
};

bool Test1::Initialized = false;
  • If the functions need to be defined right in .h you may use a namespace with a special name within a "public" namespace. Usually that namespace is named `detail`. Take a look into libstdc++ or boost headers to get the idea in all gory details – user3159253 Oct 10 '14 at 21:41
  • Actually, the deprecation of `static` for TU-local symbols was taken back in C++11. – Deduplicator Oct 10 '14 at 22:10

1 Answers1

7

You don't need to expose private details in the public API:

foo.hpp:

#ifndef H_FOO
#define H_FOO

namespace Foo
{
    void Start();
}

#endif

foo.cpp:

#include "foo.hpp"

namespace Foo
{
    namespace
    {
        void ProcessStart()
        {
            // ...
        }
    }

    void Start()
    {
        ProcessStart();
    }
}

Only the header file ends up in your public /include directory, so nobody will ever know that there are private implementation functions (except perhaps your debugger).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084