1

Can someone clarify what this means at the top of the file in C++?

using std::cout;

Thanks

1

5 Answers 5

8

It means that from then on in the code, when we type cout we mean std::cout

It injects the cout defined in namespace std into the current namespace. We use this over using namespace std as this is much more controlled; not every single std name will be injected with this statement.

3
  • but usually when i type "cout" in general it works fine. I have never really used std::cout, which is why I am wondering. Found this interesting and did not know what its purpose was Commented Oct 13, 2012 at 22:03
  • Did you type a using namespace std; before? Because this would do the same thing (Except for endl swap and tons of other stuff) Commented Oct 13, 2012 at 22:11
  • i always define it like this... using namespace std; but i think i see it now Commented Oct 13, 2012 at 22:13
0

It's a namespace declaration. Allows you to type out cout instead of std::cout and is generally preferred instead of using namespace std;

0

The using declaration introduces the name cout to the global namespace as a synonym for std::cout.

0

It is related with the "namespace" concept. In order to avoid name collisions (variables, classes, whatever, which have the same name in different files), you can put your code into a namespace as following:

namespace exampleNS
{
    class A { ... }

    void aFunction (...){ ... }
}

When you are inside namespace exampleNS, you can refer to class A using just the name, but from outside you need to write exampleNS::A.

If you want to save the verbosity of adding the namespace before a name that you use a lot (and you are sure does not collide with anything inside your current namespace), you can write that using statement.

Mostly all standard library utilities are inside namespace std, as for instance the variables cout and cin. In your case, your code is not inside the namespace std: you can choose between writing std::cout each time you want to print something, or write using std::cout at the beginning and then using it as cout in the code.

0
using A::B

Where A is a namespace, means that accessibility of B does not require the prefixing of it's derivative. Note that this is only relative to the scope in which it is placed. If placed in a lower-level scope, it's function will not have any affect in the outer scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.