Q: Why do I get compiler errors for the following code?
A: Including the header where identifiers (whether that means classes, structures, functions, etc.) are declared is not sometimes enough. In the C++ Standard Template Library everything is declared under the namespace 'std'. That means the fully qualified name of 'cout' for example is 'std::cout'. Not using this fully qualified name yields a compiler error. Thus, the correct code should look like this:Code:#include <iostream> int main() { cout << "hello from the third planet from the sun" << endl; return 0; }
Code:#include <iostream> int main() { std::cout << "hello from the third planet from the sun" << std::endl; return 0; }
Q: Is there a way to avoid using the fully qualified names all over my programs?
A: You can avoid that by loading the identifiers from a particular namespace (in our case namespace std) into the current namespace (which in the case of the main() example is the global namespace). This can be done in several ways with the 'using' declarations and directive.
The using declaration introduces a name in the current namespace. The name becomes an alias (or synonym) for a name declared elsewhere (another namespace).
The using directive allows all the names in a namespace to be used in the current scope without explicit qualifying using the namespace name.Code:#include <iostream> using std::cout; // cout becomes a synonym in the current namespace for std::cout using std::endl; // same for endl int main() { cout << "hello from the third planet from the sun" << endl; return 0; }
Notice that since the using directives loads all the names from a namespace into the current namespace it is not a good practice to use it in headers, because it can lead to loading namespace's names into places where they are not needed, since a header is most likely to be included in source files where the identifiers from the namespace will not be used.Code:#include <iostream> using namespace std; // everything from std is now accessible in the global namespace // without fully qualification int main() { cout << "hello from the third planet from the sun" << endl; return 0; }
A third option of mapping namespace's names into another namespace is using namespace aliases.
Code:namespace A { namespace B { class foo {}; } } namespace C = A::B; // C is an alias for A::B C::foo f;




Reply With Quote