Can we use namespaces like in below snippet? The code compiles in both gcc and msvc, leaving me confused about namespace usage.
In f1.h:
namespace My
{
void foo();
}
In f1.cpp
`
void My::foo()
{
}
I thought that the function should be defined as:
namespace My {
void foo() {}
}
Can anyone kindly explain?
Thanks
It’s legal to define namespace members outside of their namespace as long as their name is prefixed with the name of their namespace, and the definition actually occurs in a namespace that encloses it. It can’t happen in a namespace that’s nested inside the member namespace.
It’s the same stuff as for class members, where you can also define functions outside of their class, as long as you prefix the names with the name of the class. However as for classes, namespace members must be first declared in their respective namespace before they can be defined outside out it.