Difference in loading times with and without namespace - c++

I'm fairly new to C++ so I hope this question isn't dumb, plus I've searched around and couldn't find an answer.
So this brings my to my question, is there any difference in loading times between calling std::cout and calling cout when using namespace std is added to the code? I imagine that if there is a difference it should be unnoticeable, but I'd like to be sure before turning in my project.
By the way, in my university we are told that using namespace std is okay (I've already read at lengths on that and whether it is good practice or not is not in question right now).

There is no difference. And performance should be the last of your concerns when making these kinds of "micro" code decisions.

Related

What does using something::something::something mean (c++)?

So I just started as an intern and the code that I'm supposed to be working on is scattered within like 10 different directories and 100 files and who knows how many namespaces. I've never worked with this before, and I'm really confused how they are all being linked together.
I keep seeing these sorts of statements one after the other, ex:
using something10::something2::something6;
using isThisANamespace::iHaveNoIdeaIfThisIsAClassNameOrWhat::something599;
using randomName::otherRandomName::randomName99999;
using something4::something3::something8766678788787987987698;
Whenever I try to google what using does, I only find results with using namespace. Is using now just a shorter way of using namespace? Some of the things they are using appear to be folder names and file names though. My company mentor doesn't know c++ so he can't help me alas.
Also, if these are all namespaces, then wouldn't using so many of them conflict? Can you call namespace::classname::function? And when you do this do you still have to include the filename for that class?
Please help me learn how to call a function buried in another directory that is also in 4 namespaces. I'm very lost.
This is a using-declaration. It introduces a single name from another namespace into the current scope so that it can be used without qualification. It's not the same as a using-directive, which begins with using namespace.
check below link, hopefully it will help you on what you are looking for
https://www.tutorialspoint.com/cplusplus/cpp_namespaces.htm
If there really just random naming, than it's very-very bad. BUT I hope it's just yours personally vision, as beginner in C++, and in reality there is a good code, but kinda complex.
I don't know yours background, what languages you know, so I would say that namespaces are kinda boxes. They can build very good, hierarchically structured, modules\subsystems. I suggest you to not panic, take paper and try to wrote out all namespaces, their relations, what is in them (classes, structures, maybe functions) and your own understanding them purposes.
P. S. sorry for bad English. This topic very close for me, but my writing skills in English are not very good for a free conversation about this. I hope moderators will fix typos.

Adding a namespace vs adding std:: to every line of code [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 6 years ago.
I've been coding for many years as a hobby and I'm now studying computer science which is a great way to answer the "why"s as well as the "how"s of the programming world. I've seen many great code examples across multiple message boards including this one and I'm wondering why some people would rather add "std::" to every single line of code rather than just adding "using namespace std;" once and never having to worry about it ever again. I understand some projects involve multiple namespaces, but what about the ones that only use "std::"? I hope someone might be able to shed some light on this, and I'm sorry if this comes off as a dumb question.
Thanks!
Well, if it is not a matter of coding style, people including myself here usually goes to "std::" to avoid name collisions that may happen when you start "using" a few namespaces in your code.
By specifying the entire scope (ex "std::string") of a type you are reducing the name collision risk to pretty much zero.

Is it a good practice to refer to a particular item with "using"?

For example, I know I will only need "cout" from the std namespace in my code, so I'll refer to it as:
using std::cout;
So I can freely use it as:
cout << "Using namespaces like a boss!" << std::endl;
Instead of bringing the whole namespace to my code.
I'm very used to typing everything prepending std as I was told using the namespace was kind-of a bad practice as it can cross with other functions in other namespaces (Fortunately, it has not been the case for me, I'm still learning to code and I'm in second semester of my career), but instead of prepending std to everything, I'd like to do "using std::cout" and other stuff like that so I can improve readability in my code, which is important for me to understand my code later at some point in time.
It is a bad practice to universally label things a "bad practice" as a substitute for discussing the real problems and trade-offs.
Some techniques can be bad and are misused often. The using and especially using namespace directives can be misused, so a cookie-cutter mindset is to just say they are somehow "bad".
Inside a single .cpp file, you have more control over the namespace(s), so using std::cout at the file scope or even using namespace my_funny_namespace is fine as long as the opportunities for clashes are manageable and there is some gain in readability. At some point, perhaps if the .cpp file gets complex, you run the risk that a new name gets added to some_funny_namespace that clashes with one of your names and using namespace some_funny_namespace would bring in something that would break your code. But this might be less likely with something stable like boost or std.
You can also use using locally, per-function. But if most functions in the file need the same declaration, D.R.Y.
Where it can cross the line into a really bad thing is when you use either of these in a header. Then you have leaked names from another namespace into every file that includes your header too. See this great answer for alternatives and discussion. This is really bad because it can cause spooky action-at-a-distance bugs when including or not-including a header causes some completely unrelated problem to show up or disappear. And it isn't just "your" code that might break, it could break someone else's code that uses your header.
Don't leak names into other namespaces
So using and especially using namespace is verbotten in headers? What if the header is for internal use within a select set of .cpp files? Then, maybe it's OK. That's the problem with cookie-cutter rules, there is always an exception and making some hypothetical thing worse for no reason but best-practices is terrible.
The upside to using is readability (which should not be under-rated).
The downside is the potential for name clashes, especially unpredictable ones in some other random code.
Choose wisely. Carefully considering all aspects of your design is the good practice.
(and asking good questions isn't too bad either).
usingnamespace::identifier; is part of the language because in some programs it's helpful. You're balancing concision and flexibility against fragility, but the worst that can happen is you have to step in to resolve a compiler error by disambiguating which cout object you mean. If you're just using a handful of identifiers from a large namespace, having targeted using statements is often a reasonable compromise; if the list starts to get overly large then using namespace std; may become easier.
Neither should be used in at file scope in a library's header file, as they'll stay in affect for the rest of the translation unit and make break client programs.
Within confining scopes, and within implementation files (.cpp, .cc or whatever extension you use), you can basically afford to experiment with using and fix ambiguities as necessary - you'll learn what works best for you.
using std::begin; and using std::end; are good examples of particularly useful using statements, as they allow begin(my_container) to match std::begin() when the latter has an overload for my_container, but if my_container's begin is actually in whatever namespace the container's declared in, begin() can still match due to Argument Dependent Lookup.
Tip: it's usually better to write [std::]cout << "Using namespaces like a boss!\n"; - more concise, and why force flushing? It tends to degrade performance, and cout is tied to cin so flushing will happen when needed for prompting for user input....

C++ Namespace Noob Needs Assistance

I have run into some quirks about my code style that I'm hoping to fix, namely with namespace usage. Let me begin by saying that I am currently employed as the sole software engineer on my particular project and don't have access to more senior level engineers to mentor and assist me. I find this particularly worrisome since I'm concerned that I'm developing really hacky practices that will get me laughed out of the room when I attempt to change jobs in the near future.
Recently I have been following and conforming to the Google style guide. I was a bit shocked when I learned that the process I had of always doing "using namespace std;" is frowned upon. In generally, most of my projects have been relatively small with little chance for reuse of my classes. However, now that I've done more research and studying, I realize why my practice is frowned upon and I'm looking to improve the way I use namespaces and the scope operator. As a result, I have the following questions:
When is it best to define a new namespace? I know that this is a weird question, and I understand that functions or variables that don't belong to a class can be group together in a namespace. However, say I have a program composed of solely classes. Is it bad practice to not define a namespace? Or should a new namespace be created solely for the project in case someone wants to interface with it later?
I know this has been argued ad nauseum, but when is good to use "std::"? I ask because I recently read up on how its better to use the "wrapped" versions of the C standard libraries (e.g., cstdlib vs. stdlib.h). I changed some of my source code over to experiment. I immediately found it weird that G++ didn't yell at me for not using std::printf() instead of just printf(). The question I have now is where do I stop in terms of the explicit scope placement? For example, the compiler doesn't yell at me about size_t or uint8_t, do I have to place "std::" in front of those as well? What is considered best practice?
Is it considering "ok" to call "using" on only the functions that you are using? Namely, I'm speaking to a case where I have a class and would do something like "using std::endl;" in the .cpp file that implements a particular class.
Edited to add a fourth question:
4. When writing code for a derived class, does it make sense to do "Baseclass::function()" whenever calling functions from the base class, even when the functions from the base class are not virtual and cannot be overloaded? Does this hinder or improve readability?
Thanks for all the help. I find this site to be a great resource!
These are practices that have served me well over many years. Hope you find this helpful.
1) Namespaces are an organizational technique for keeping like things together, usually for discoverability and to avoid name collisions with other code. They can be a great aid help when you're using intellisense-capable IDEs, making it easy to code without having to bounce back to docs to find something. Excessively fine-grained namespaces can be as detrimental to your code as no namespaces. While there's no hard rule here, but if you're consistently creating new namespaces for groups of less than 3-4 items, you are probably overdoing it. You also wouldn't typically define new namespaces inside a .cpp file, since that's the only file that would see it. I rarely see examples of the other extreme.
When working with templates, where everything is in headers, I like to create a "details" namespace under the main namespace to isolate the 'private' classes of the template library from the things that people are actually expected to use. There are other ways of achieving similar results that provide better encapsulation, but they are also more work to maintain.
2) Using statements should typically be isolated in C++ files, and not placed in headers, otherwise you lose track of what is 'used' pretty quickly in large projects. Similarly, it's best for portability and maintainability if your headers don't implicitly rely on using statements. You can make this easy to avoid by placing your using statements immediately after your include statements.
// main.cpp
#include "myheader1.h" // can't see using namespace std, ok.
using namespace std;
// Does this have std:: in front of everything that needs it?
// Maybe. Compiler won't tell me...
#include "myheader2.h"
Never put a using statement inside of an open namespace. That is, unless you really, really want to make peoples heads spin. This likely won't work like you (or the next guy) expects.
namespace A { ... }
namespace B {
using namespace A; // Don't do it!
}
In some cases, for absolutely ubiquitous namespaces, I see people put using statements in precompiled headers (is that just a VC++ thing?). I find that tolerable because they're usually local to a smaller body of code, though even there I think it's a stretch. It can facilitate the header dependency problem mentioned above.
3) That practice can get to be a nuisance, because you'll find that you have to keep going back for 'one more thing' and it can be confusing ("Wait, for this file did I use math::vector, physics::vector or std::vector?"). If you can't use the entire namespace because of collision issues, it may just be better to be explicit about at least one of the namespaces. If there's a lot of overlap, and maybe be explicit about both.
In some rare cases, with deeply nested namespaces, it may be useful to write something like this:
using namespace this::thing::is::ridiculous::someone::should::trim::it = ludicrous;
That allows to reference the namespace with a short moniker, e.g.
auto p = new ludicrous::SomeClass();
If you are going to do that, you should establish consistent conventions throughout the codebase for the namespaces that you do that to. If you use 3 different names in 3 different places, you just make the code less readable.
Anything that is designed to be at all reusable should use a namespace. Anything that has a name that has any possibility of name clashing should use a namespace, and this means pretty much anything. With smaller projects, it matters less, but in general, everything should probably go into a namespace of some kind.
Based on the C++ standard, anything that comes from a C++ standard header will be in namespace std. They may also be yanked into the global namespace. Hence, you should prefer to use std::printf or std::uint8_t and the like for maximum portability.
It's a matter of preference. For basic things that are in the std:: namespace, I'd rather be explicit personally, since it's so few characters to type. For highly nested namespace names (like some parts of boost where there are 3+ namespaces to go through), then using makes more sense.
My preference is to use std::cout for example, in other words ::FunctionName().
1. In my opinion this makes the usage obvious/explicit to reviewers/readers of the code.
2. The "using namespace " ends up including all classes of that namespace and consequently may result in clashed with your class/function names.
3. If one knows that whatever one is developing is a library creating it in its own namespace is a must.
4. For classes that are not going to be developed/interfaced to third parties, I wouldn't bother with namespaces.
Let me know if this answers your question. Otherwise come back for more detail.

Sample C++ tests

I'm about to take a C++ test. But I only get one crack at it to get over 85%. If I don't push over that, then I don't get the job.
The problem with these tests are that they typically target generic C++, and depending on what libraries you use your definition of generic may differ. STL and Boost may seem logical to some (and should be part of most) but I worked with MFC for years before ever using templates. Why use >vector> when you've got access to CArray? (retorical question)
If you've worked with dialogs you've not used stdio. If you've worked with Borland products you've not used MFC. If you've worked with Palm, you've not used the file system, and you've definitely not used CFile.
OK, so here's the question...
Given that I'd like to pass the 85%, I'm taking online tests of "generic" C++. So... Is there a place I could go to find tests? The more the better. Correct answers are also good, either during or after the test. As long as I can learn from my mistakes.
EDIT: If your answer doesn't have a link to a test, some C++ questions, or some interview questions... You missed the point of Is there a place I could go to find tests?
Great example.. I've just found this question.
What does the following code fragment print? cout << setw(6) << setfill('#') << "Hello";
I've been coding for 9 years. And never used cout, setw or setfill once. Not since university.
Erase all the MFC from your head for now. Go pick up a book like The C++ Programming Language, and try to learn the concepts front to back. You should be fine. If they are asking for more than this, I don't want to know what their definition of "generic" is.
The few times I've been "tested" (well "interviewed"), folks were far more concerned with questions like:
What is Object Oriented Programming? OOA (analysis)? OOD (design)? UML?
When should you inherit from a class? When should a class be aggregated?
What are virtual methods? What are pure virtual methods? What is the vtable?
Sibling cast problem. class C : public A, public B; C c; B * b = & c; How to cast object b (type B*) to an A*?
What does the stack look like as a simple program executes?
Differences between heap/stack?
How does new() differ from malloc()?
etc.
There's lots of previous discussion on C++ interviewing questions here on StackOverflow and elsewhere:
https://stackoverflow.com/questions/240212/
what-is-the-difference-between-newdelete-and-mallocfree
https://stackoverflow.com/questions/347793/
c-areas-you-look-for-during-interview
https://stackoverflow.com/questions/365823/
what-kinds-of-interview-questions-are-appropriate-for-a-c-phone-screen
http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html
Just to add my two cents here: If they are looking for graphic details... To see if you've memorized the entire C++ spec... Well I know the economy stinks right now but it is improving, there are other jobs out there, and you NEED to find one of them. Interviews are a two-way street. If they are into nit-picking details, this is NOT a place you want to work.
You might try Herb Sutter's book Exceptional C++; it contains items organized like questions and is, in my opinion, very clear and very well written. I don't know if it will be directly useful for the interview, but it makes you think about aspects of the language you had never considered before.
It's been a long time since I last visited it, but you might also try this site with interview questions: geekinterview.com - take a look in particular at the C++ section.
All the best for your interview :)
What does the following code fragment print? cout << setw(6) << setfill('#') << "Hello";
It prints the following sentence to standard output:
Please do not work for us. We have no clue about what it means to be a
good software developer.
I found these.
http://www.acuit.com/_vti_bin/shtml.dll/Test_C++.htm
http://www.acetheinterview.com/questions/cats/index.php/algorithm
http://www.faqs.org/faqs/C-faq/faq/
http://www.coolinterview.com/type.asp?iType=41
http://www.radiussg.com.au/Candidate%20Interview%20Guide.pdf
http://www.eecs.utoledo.edu/~ledgard/oop/left.html
Some questions in FAQ's might work as tests.
IF you are going to give tests for job then brainbench tests may help.
I guess C++ tests are free and you can get some idea of what kind of questions you can get.
Good luck for tests!
During interviews I bother about the candidate being able to show me that he/she understands what he's/she's doing and that he's/she's leaning toward "modern" C++ (i.e. template intensive).
He/she also needs to understand some subtilities of the languages, but not the most arcane. I don't ask tricky question that are based on the oddities of the language. Why?
STL mastery is a pre-requisite. I see knowing nothing about Boost as a bad sign.
If I were to write a test, I would make it quite easy just to filter the really bad programmers that don't master the syntax and the logic of C++. I however prefer a one hour one-to-one interview to filter candidates.
If you find yourself fighting against a very hard written C++ test : run away.
I hope this helps.
Edit : if you really want tests and questions, check this out : http://www.gotw.ca/gotw/
There are a few free tests here and they have explanation videos on youtube for a few of the questions.