Namespaces in C++
Patreon ► / thecherno
Twitter ► / thecherno
Instagram ► / thecherno
Discord ► thecherno.com/discord
Series Playlist ► thecherno.com/cpp
Thank you to the following Patreon supporters:
- Dominic Pace
- Kevin Gregory Agwaze
- Sébastien Bervoets
- Tobias Humig
- Peter Siegmund
- Kerem Demirer
Gear I use:
-----------------
BEST laptop for programming! ► geni.us/pakTES
My FAVOURITE keyboard for programming! ► geni.us/zNhB
FAVOURITE monitors for programming! ► geni.us/Ig6KBq
MAIN Camera ► geni.us/t6xyDRO
MAIN Lens ► geni.us/xGoDWT
Second Camera ► geni.us/CYUQ
Microphone ► geni.us/wqO6g7K
Пікірлер: 176
The "::" is called the scope resolution operator.
@guestimator121
4 жыл бұрын
I've called it "that thing" for almost 20 years now. Not gonna change it now.
4 жыл бұрын
@@ic6406 It's surprising how much you can actually recollect with watching videos that is about your profession.
@mangalegends
4 жыл бұрын
@@ic6406 sometimes you forget stuff and have to refresh your memory
@mamertvonn
3 жыл бұрын
@@ic6406 awww sh*t... Ya just got UnoReverseCard-ed
@GrantSR
3 жыл бұрын
@@ic6406 Sometimes, I watch videos about something I already understand to see if that KZreadr actually knows how to explain things and knows what they're talking about. Then I know I'm relatively safe watching their more advanced videos.
Hi cherno I would love to watch your explanations for design patterns in c++
@luanbaviloni6714
6 жыл бұрын
Dave Wallace I agree with you. Great topic!
@ricardo.mazeto
6 жыл бұрын
Totally agree.
@ZestyMuffins
6 жыл бұрын
yes cherno explaining design patterns would be very good
@yashmalviya4563
5 жыл бұрын
Yes please.
@groberti
5 жыл бұрын
@mrtrex01 Well, not really. It is key not to overuse them. People love to apply them to everywhere and anywhere but I'd rather have a programmer who knows some design patterns but would rather think about the given problem and might even customize it rather than one who applies them blindly to anything and everything. They are good for expanding ones view of the "programming world" but should serve as guidelines rather than something that is written in stone.
Cherno's hand gesture in the beginning of his vids is literally something out of a videogame. The movement is so smooth.
@67hutch
Жыл бұрын
LMAO true
The best explanation of Namespaces I've found so far!! Thanks a lot Cherno!!!
you are incredible. you make hard to understand topics so much easyer to learn … thank you
In C++ 17 you can nest like this: namespace orange::apple::fruit etc. (It's my favourite feature.)
@BlackJar72
6 жыл бұрын
Well, I never thought of it and just thought you'd be able to -- basically makes it like Java / C# with there import / using statements.
@TomoyukiAota
5 жыл бұрын
Before C++ 17, for nested namespace, I would do namespace orange { namespace apple { namespace fruit { // some content with a single indent }}} instead of Cherno's namespace orange { namespace apple { namespace fruit { // some content with a single indent }}}
@HermanWillems
4 жыл бұрын
@@BlackJar72 Wait for C++20 with imports. GOING to be ALOT better !! :) C++ is evolving quickly to the right direction
You are such good teacher! Loved the vid
Constantly waiting for the dude to accidentally smack that cactus with the back of his hand.
Thank you for the great videos. This is my first day watching your videos. And i love your explanations! And for some reason, the videos you made are so easy to watch! 12mins video ended quickly as if it was a 3minutes vid.
Thank you for this video. I am studying this now in university. It makes more sense now that I understand why you would use it
Quite a chill video. Enjoyed it
This was explained so simply, thanks much!
Tons of confusion cleared. Thank you.
This is awesome, cleared up a lot for me!
Thanks for this quality content!
Thanks for uploading :D new content
now i love namespace
Very helpful video, thank you!
Thank you for the concise explanation!!!
@7:17 below my mind! That's the exactly answers to some of my questions regarding using namespace in C++; Thank you Cherno! You are extraordinary amazing!
Wait, so if you think about it, namespaces are used to avoid name conflicts, and "using namespace" is an intruction to remove that namespace, but you may have name conflicts again, since the functions in that namespace no longer have an id, so "using namespace" is actually like losing the point of namespaces
@Willifordwav
Жыл бұрын
Correct, that’s why most experienced C++ devs do not do it
@Anonymous-hv7fh
8 ай бұрын
But if there is a name space that you use often like std for exmple "Using namespace" Would be helpfull And if there is a commun name just use the :: to specify it Isn that better
Really cool, thank you !
Thanks for the video, it help me understand what namespaces are. Well explained
I would have loved to hear something about anonymous namespaces . But nice video anyway ;)
@zdanek
3 жыл бұрын
Yeah, that was my thought also. They are very useful for introducing local scope functions. Maybe many other properties which I don't know.
Simplest explanation 👍
I would love to watch TheCherno's explanations on data structures :)
@thestarinthesky_
4 жыл бұрын
you can check MySchoolCode channel on KZreadl! It is one of the best channels too!
Excellent! Thanks
Thank you!
I was watching on 1.25 speed and after a few minutes i forgot about that and got surprised and impressed by the speed of your typing lol
Thanks TC!
Thank you. You made so easy.
"Back in the days of C". Me, a C Developer: 😢
hi cherno thanku very much for this tutorial
Maybe it’s because as a professional, I used Java and automatically appreciate how Java does things because I’m familiar and therefore comfortable with it, but I always liked the idea of just importing specifically those classes that you need. You can import all the classes within a package, side but that’s not a good practice. Once you import a class into your source file, you can just use that class name directly. In C++ the practice is to always use the objects and classes with their full namespace prefix, rather than “using namespace::class/object” If there are name conflicts, which isn’t all too common, but if there are, you import the one you use more and use the fully qualified name for the other(s)
I don't know how do you do that, but after watch more than 60 videos, you still able to maintain the quality and didactic. Thank you!
I wish my first C++ professor (courses 1 and 2) would have covered namespaces at this level of detail, granted he was already trying to crush a lot into the time he had, but it seems rather important if you ever need to use a library other than std.
@Yupppi
6 ай бұрын
That's the thing though. Namespaces are need to know basis things, not really core to learn to write useful programs. Once you have passed that level in coding, you most likely will have studied more, either formally or by yourself, and will learn about namespaces because they become relevant to you.
@mytech6779
6 ай бұрын
@@Yupppi They are part of the core language and used to some degree in every source file, so they are needed to write useful programs. It isn't necessary to know every syntax detail but the subject should be known a fair bit beyond a blindly adding "using std" at the start of every file.
Hi dude Awesome videos so far.... great job !!!! can you please create video about network--> Serialization and Unserialization that topic is confusing me :(
Also, for people coming from java or some language like that, c++ namespaces are not for organising code. Do not do namespace mylib{} namespace mylib::graphics{} namespace mylib::sounds{} namespace mylib::this{} namespace mylib::that{} etc. Namespaces in c++ are only for preventing naming conflicts. Put everything of mylib in namespace mylib, unless you get conflicts inside your library that would otherwise only be preventable by using forced naming schemes. And c++ namespaces are completely unrelated to source files. You can open and close multiple namespaces inside one source file. You can open and add to the same namespace in multiple files. Another remark. I think the only good situation for using namespace bla; is for getting literal suffixes. So you can do using namespace std::string_literals; auto x {"bla"}; // x is const char* auto y{"bla"s}; // y is std::string, thanks to the s suffix that is defined in std::string_literals It's a pain to use these suffixes without importing the namespace.
Good tutorial. ty.
the baisc purpose of the namespaces is to prevent the naming conflicts
really good tutorial i finally understood why namespaces were invented
thanks
I found out that I press like button then I watch your videos, because I believe it will be an awesome one :)))
Thanks this saved my skin when trying to modify a simple hello world example. I forgot all about name spaces not used in 20 years living in a blitz max basic world..
The c++ committee has solved the nested namespace thing. Nowadays you can say namespace apple;;functions { //... } and that is the same as namespace apple { namespace functions { //... } }
best tutorial ever!!!!!!!!!!!!!!
Great content, as usual! Just one question, In the performance side of things, is there any difference to do a struct or even a static class other than use a namespace? Once I can aswell have variables inside namespaces. I mean, does namespace has any gain once it does not carry all OOP stuff (Inheritance, Polymorphism etc) with it?
@darkengine5931
3 жыл бұрын
No performance diff and I tend to suggest erring on the side of static methods in those cases mainly because of the fact that namespaces offer using directives, using declarations, and argument-dependent lookup. I remember a colleague of mine trying to use namespaces this way. He used something like this widely as a convention: namespace SomeSystem { void startup(); void shutdown(); } ... except he used this convention for multiple systems. And it resulted in some goofy bugs among the team that ended up calling the wrong startup/shutdown functions. Can't possibly encounter that problem with: class SomeSystem { public: static void startup(); static void shutdown(); }; And of course, you can still add static variables here if you want to code things this way, but unlike namespaces, you can give them something other than public scope. Namespaces are there to avoid clashes between identifiers. That's it. I really don't think anyone should be using them to model anything remotely resembling an object.
I'd find it very tempting to use them like Java imports (which really are basically a kind of namespace), thought perhaps the abbreviation method would be more controlled. (C++ has inner classes ... how do they compare to Java ... now I'm curious....)
You are a great teacher man!
What would it mean for a variable or function to be static inside a namespace? Can you have private functions in a namespace which are only visible to other functions in that namespace?
nice!
love my friend
Hi Chemo, thank you. Please tell me namespace has nothing to do with physical directory location ? eg 2 functions with identical name in directories /a/b/print.cxx and /a/b/c/print.cxx can still be confused by compiler? Thank you!!
Great! !!
could you please make a video about C++ threads?
Hi, I'm relatively new to programming and C++ but I already can write some small programs. Now I'm looking for a somewhat bigger project for me to code, just to learn the language and all. Do you guys have an idea? Thank you!
In the c++ standard library are all the libraries there using the namespace std?
I know this is 5 years ago, but nice haricut! 💇🏼
genius
Query - if we have two namespaces apple and orange that have a print() func with same signature then no error is reported till call to print() is made. But why does the compiler not report error on specifying the namespace itself. 1. using namespace apple; 2. print(); 3. using namespace orange; 4. //print(); Error "error: call of overloaded 'print()' is ambiguous" on uncommenting statement4 but no error after commenting it.
So using namespace a = apple is like "import numpy as np" in python?
How do I decide whether I should make a class or standalone functions? Often I feel independent functions are better but then sometimes I might need a variable to store something outside that function and then maybe a class is better but then i would have to create an object and call that method from that object instead of just using a function and i am always so confused
@M4gicT0
6 жыл бұрын
Well you would use a class when the functions you wish to implement can be related to each other, like if they all relate to the same thing... When your functions share data between each other, then you need to write a class because it makes everything much easier and creates a scope for the data. However if you only want a few functions to be separated in a class, but don't want to instanciate that class each time because you feel that you don't need to, then simply use static functions / variables ! Or if they are just helper functions that don't store any data, well you could as well use a namespace for those...
Cool video :) Could you maybe also make a video on C++ Iterators, I find them sort of confusing^^
@HermanWillems
4 жыл бұрын
Which one the OLD one, the Previous one or the Ranges-V3 version?
- help, he needs a doctor - I'm a doctor - help - can't - why - I'm a doctor::law()
Can't the name printing thing be done at the end?
A namespace inside a namespace - talk about organisation. 🤯
Love the content. You can comment/uncomment a line using shortcut ctrl+/
Neither do I like namespace. But the problem is, if other programmers are using it, and you are working in teams with them, or working on / extending / modifying their code, then you've got to undestand namespace. Unless you are an absolutely solo programmer, developing everything on your own from scratch.
@darkengine5931
3 жыл бұрын
I've fortunately been with teams that steered clear of them, but they were eclectic teams that consisted of a mixture of C and C++ programmers and we had a C SDK/API where namespaces couldn't be used, and the conventions developed from the C SDK where simple prefix naming conventions were used to avoid clashes.
in ADA language, the synonymous of namespaces is a package, right?
Hey Cherno please make a video on how to generate random numbers in C++
if an user defines a function then in which namespace will it fall??
If you suggest not using namespaces in header files, why do you do it in your hazel building a game engine series? (video 5 entry point)
@michaeldamolsen
3 жыл бұрын
I know it is long ago you -asked- commented, but maybe others are wondering. There is huge a difference between using "namespace xyz { ... }" in a header file, and using "using namespace xyz;" in a header file. It is the last one he suggests avoiding at all costs. I just went through the video you referred to, and I did not see him type "using namespace xyz;" anywhere in it, or maybe I overlooked it somehow even though I was specifically looking for it.
@djamparo6636
3 жыл бұрын
@@michaeldamolsen Hey, thanks for commenting after all this time! I don't remember me writing this one honestly, but I have more experience in c++ right now. Using those kind of names paces is just bad practice as this is not really its intent. I don't know if it was shown in the video and I'm not really wanting to look for it, but thanks for your time! And sorry about the hassle!
I believe people will appreciate a discusion on anonymous namespaces
What are anonymous namespaces good for?
cool
Which IDE you're using.
This is sorcery
Is it okay to put namespaces around just #defines?
miss the coffee intro
@voxelrifts
4 жыл бұрын
IKR :)
how much do you earn cherno?
May I ask why we don't need to do #include ?
@gtafigosaarea5uno
2 жыл бұрын
because you're not including class vector, you're including the header file containing class vector.
Finally 0 dislikes (till now).. thank god
Will anyone ever need to put a nested namespace in any scenario?
I'm learning namespaces because Ivor Horton told me to do so.
on the opengl series, i followed up until the shader part and your one drew a red rectangle however, mine is not drawing anything at all and i have no errors (on a mac)
@somedude4122
6 жыл бұрын
That's almost certainly an error in the code. Try grabbing one of the samples onn github to see if your GPU actually supports it
@ASH-fk7wl
6 жыл бұрын
#include //VERTEX SHADER const char* vertexSource = R"glsl( #version 330 core in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } )glsl"; //FRAGMENT SHADER const char* fragmentSource = R"glsl( #version 330 core out vec4 outColor; void main(){ outColor = vec4(1.0, 1.0, 1.0, 1.0); } )glsl"; int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); if (!window) { glfwTerminate(); return -1; } float vertices[] = { 0.0f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, }; float pixels[] = { 0.0f, 0.0f, 0.0f, 1.0f,1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f }; unsigned int tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); unsigned int vbo; glGenBuffers(1, &vbo); // Generate 1 buffer glBindBuffer(GL_ARRAY_BUFFER, vbo); // Makes the buffer active glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //CREATING VERTEX SHADER unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSource, NULL); glCompileShader(vertexShader); unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentSource, NULL); glCompileShader(fragmentShader); //CREATE THE SHADER PROGRAM unsigned int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glUseProgram(shaderProgram); unsigned int posAttrib = glGetAttribLocation(shaderProgram, "position"); glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(posAttrib); unsigned int vao; glGenBuffers(1, &vao); glBindBuffer(GL_ARRAY_BUFFER, vao); /* Make the window's context current */ glfwMakeContextCurrent(window); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { /* Render here */ glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 3); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; }
@ASH-fk7wl
6 жыл бұрын
thats my code. I dont get any errors
@somedude4122
6 жыл бұрын
You bind the VAO before you do anything to the VBO. Binding the VAO effectively resets whatever happened before it.
@paulkupper194
6 жыл бұрын
Sensi ASH Watch the Episode about dealing with Errors in OpenGL. By default OpenGL does'nt do any Error handling, so there might be Errors that you are not aware of.
Can you make a video about using SPIR-V in OpenGL?
Even my typing speed does not match with this guy coding speed
which app are you using for programing
@kocho4242
6 жыл бұрын
It's Visual Studio.
Wait he said we should use namespaces throughout serious projects at the end of the video, but earlier he said that you should be using it in as small of scopes as possible?
@signalcoder2037
2 жыл бұрын
for the later namespace , he means "using namespace abc; "
Game Engine Series!
@katlehokomeke
6 жыл бұрын
Which game engine uses c++
@valizeth4073
6 жыл бұрын
Like, all.
@groberti
5 жыл бұрын
Between C and C++ I bet most of them choose C++
#include using namespace std; void hello_nerds(string name){ can't
can you please cover __declspec(/*scary_stuff*/) in your next video
can't classes also solve the naming issue
Hi
hi
The simple solution to avoid writing std::cout and std::cin and std::endl would to just use #define, cause I dont think anybody would want to use a custom cout,cin or endl #define cout std::cout #define cin std::cin #define endl std::endl
Is it not just the same as just having the name of the library like glfw and then a dot to indicate something inside the library? Like glfw.destroy()? Why does c++ use namespaces instead of doing it like that? This is just confusing for me as iostream doesn't use iostream:: or something, no that's std::?!? In Go for example you would just import the package fmt and then all the functions inside fmt are accessible by just typing in fmt.Printf for example. Why does C++ feel the need to do it so drastically differently and confusing by not even naming the namespace the same as the package name?!
But I believe the Object Encapsulation in C++, has protected symbols (mem-func()s and mem-vars) from being conflicted, to some degree. E.g. class A { void myFunc(); } class B { void myFunc(); } won't be in conflict, because myFunc() has to be referenced to, THROUGH, the higher-level symbols, Class A or B, FIRST, i.e. it is NOT exposed DIRECTLY to the GLOBAL SCOPE.
Namespace are what drove me away from C++ years ago, though I didn't know it -- I learned a version with no namespaces, and when I upgraded my OS I got a version that had namespaces. Since no one bothered to tall about namespaces I couldn't figure out why code would link and the arcane errors had no real hint. So I said, "Screw it," and switch to using Java exclusively.
That 1 dislike is by someone who uses using namespace std