iostream
is part of the standard library, here is what the "iostream.h" file would look like if you were to implement it yourself:
namespace std{
// code about cin
extern ostream cin;
// code about cout
extern ostream cout;
}
(see c++ STL cout source code)
Where is cin
and cout
actually declared and defined? Is it in #include <iostream>
or in namespace std
?
So cin
/cout
are declared and define in the standard library under the
namespace std
. This means that if you want to use it in your code you can do :
int main()
{
std::cout << "Hello";
}
If in #include<iostream>
why should we use using namespace std
?
You don't need using namespace std
, you could call std::cout
everywhere instead of cout, but you can see how this can make your code verbose and annoying to type.
using namespace std
in your whole file is actually discouraged as it could have unintended effect, usually you could use only
using std::cout;
using std::cin;
where needed.
The reason the using is needed (or the need for explicitly writing std:cout
, is imagine you have the following code:
#include <iostream>
namespace mycoolnamespace
{
class foo {
public:
foo& operator<< (const std::string& echo)
{
// do stuff
}
};
foo cout; // created a variable called cout
}
int main()
{
cout << "Hello";
// ^^^^ compiler can't know if you meant to use std::cout or mycoolnamespace::cout here!
// Potential fix:
std::cout << "Hello"
}
If in namespace std
why should we use #include<iostream>
?
By default not all function/classes from the standard library are included in your program, otherwise a simple "Hello world" program would give a lot of work to the compiler since it would need to parse all the existing classes/functions in the entire standard library. #include<iostream>
tells the compiler that you need the functions/classes available in the standard library's iostream
'file'