Namespaces in C++
Requirements:
Linux Distribution
g++
any text editor
My Setup:
Debian 10
g++ version 6.3.0
pluma
Namespaces provide a way to prevent name conflicts in projects. Anything
that is placed within a namespace is scoped to that specific namespace. Nested
namespaces are also allowed. One reason I can think of a possible naming
collision is video games. We could have a map class that represents a the game
map. If we use all of the standard namespace (“using namespace std;”) then the
compiler will put all the objects in the standard namespace into the program’s
scope. Now when the compiler compiles the code, it doesnt know if your map
object is represented by std::map , or your map class. If I am working on a
larger project, I may break it up into multiple modular namespaces. To declare
a namespace, you just write “namespace NAME” and encapsulate it as such:
#include <iostream> namespace foo{ int bar(int baz){ return baz + 5;} // example function //other content of foo } int main(int argc, char **argv){ std::cout << foo::bar(7) << std::endl; // calling bar from foo namespace return 0; }
Namespaces can also be nested as such:
#include <iostream> namespace ex{ namespace foo{ int bar(int baz){ return baz + 5;} // example function //other content of ex::foo } //other content of ex } int main(int argc, char **argv){ std::cout << ex::foo::bar(7) << std::endl; // calling bar from ex::foo // namespace return 0; }
One other time I’ve come across naming collisions was when I was working on
a template vector library, I will get into templates soon, but ultimately I had
a class named vector. This could represent any type of vector of any size based
on the template passed in. The vector was not the collections type vector, but
the mathematical vector you would find in mathematics. The kind that have an x
and y variable, x,y, or z variable, or x,y,z,w variable based on if you passed
in 2,3, or 4 into the template. Main point of the story, if I had used the using
statement, then I would have had naming conflicts with std::vector. I know this
tutorial may have come off more of a blog-like post, but if you have questions,
feel free to comment and ask away !