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.
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.
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();
}
};
//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.