Search code examples
c++c++11namespaces

How to make the code snippet contains anonymous namespace defined in class work?


How to make the code snippet below work?

#include <iostream>

class MyClass {
public:
    namespace { // Anonymous namespace declaration
        void internalFunction() {
            std::cout << "Internal function called" << std::endl;
        }
    };
public:
    MyClass() {
        // Access anonymous entities
        internalFunction();
    }

    void doSomething() {
        // Access anonymous entities
        internalFunction();
    }
};

int main() {
    MyClass obj;
    obj.doSomething();
    return 0;
}

What I want to do?

I have some plain functions which would only be merely useful for a class. So, I think they should not be defined outside the said class. And since they are plain functions, I think namespace is better than class.


Solution

  • If you want a piece of code that is used only by the class but makes no use of class object, there are two usual solutions.

    1. private static functions, the default solution:
    class MyClass {
    private:
        //inaccessible to outsiders but still visible in the header
        static void internalFunction() {
            std::cout << "Internal function called" << std::endl;
        }
    public:
        MyClass() {
            // use the implementation detail nobody outside has to know about
            internalFunction();
        }
    
        void doSomething() {
            // use the implementation detail nobody outside has to know about
            internalFunction();
        }
    };
    
    1. A function in anonymous namespace in the implementation file. Useful if the function has some type in its signature you don't want to expose:
    //in my_class.h
    class MyClass {
    private:
        //dear clients, nothing to see here    
    public:
        MyClass();
    
        void doSomething();
    };
    
    //in my_class.cpp
    #include "my_class.h"
    
    namespace {
    void internalFunction() {
        std::cout << "Internal function called" << std::endl;
    }
    }//namespace <local> (useful to mark closing namespace bracket with a comment)
    
    MyClass::MyClass() {
        // use the implementation detail nobody outside has to know about
        internalFunction();
    }
    
    void MyClass::doSomething() {
        // use the implementation detail nobody outside has to know about
        internalFunction();
    }
    

    Notice that using anonymous namespaces in header files (where class declarations usually go) would be a horrible idea even if it worked: it would create a copy of your internalFunction() in every compilation unit. Which is not only ineffective but can break your code if, say, internalFunction() uses static variables.