Search code examples
c++namespacesprivate

Is it acceptable to not include all function declarations in the header to create a "private namespace"?


I've been writing some code for a while now. I've been using namespaces to separate a few parts of code to make the code more readable. However, I ran into a problem where I wanted to make something in that private. Here's what I found works:

//foobar.h
namespace foo_bar {
  //Other items here...
}
//foobar.cpp
namespace foo_bar {
  //Other items here...
  void foo_barz() {..
    //Faked private method!
  }
}

It compiled fine. Is there any negative to using this method? I think a class might have been a better choice for this, but using a namespace, at the time, seemed like a simpler solution because it was all one project. Is there a more "conventional" way to do this? Is this likely to cause other issues down the road? What might some issues with this be?

EDIT: I guess I wasn't clear what I did. What I did was this: I didn't include the function prototype in the header file, so when included, the header file makes the code which the file was included into think that the function doesn't exist.


Solution

  • To make foo_barz really "private" (i.e. not have its name accessible from other units), place it in an anonymous namespace, not foo_bar:

    // foobar.cpp
    
    namespace   /* stuff in here is only visible within this unit */
    { 
        void foo_barz() { ...
    }
    

    If you wanted to declare that function before defining it, you could add:

    namespace 
    {
        void foo_barz();
    }
    

    because multiple unnamed namespaces in the same unit actually all refer to the same unnamed namespace.

    Another way to achieve the same thing is to declare the function as static:

    static void foo_barz() { ...
    

    which may be done inside or outside of a namespace. Some people disapprove of this option (for reasons that are not clear to me).