I’m migrating to C++ from C and the very first thing I’ve noticed is the redundancy of prototyping inside of a namespace. I’m trying to utilize the functionality of namespaces to keep my additions/modifications clearly marked.
namespace ns {
void sayHello (void); //<-- NOT REQUIRED, BUT IS THERE ANY PURPOSE?
void sayHello (void) {
std::cout << "Hello world!";
return;
}
}
int main(int argc, char *argv[]) {
ns::sayHello();
}
Previously, in C, it was good measure to have a prototype so you would not be required to write your functions “above” main() in the source. It appears to me that namespaces must be defined before usage, so therefore, any nested functions would also be written before usage.
I’m just starting C++ and I want to start out correct. I’ve been reading several tutorials across the internet, but they don’t really mention this topic. I know this is “simple”, but please spare me the down votes and flip comments. If someone is able, I would appreciate a deeper discussion of whether or not this is obsolete, and/or scenarios this could end up biting a new C++ developer.
Not necessarily. Declaration and definition are still different concepts. Also, note that a namespace can span through multiple files and definitions are not required to be in the namespace.
Separation of implementation in C++ is done for reasons like keeping your code secret, faster compilation (changing the definition in the header would require a re-compilation of all including files), hiding implementation details or a cleaner structure.