C++/std

Advertisement


Question
sir, what is the use of namespace std in c++ codes?
and what does standard input/output streams mean?
are they objects of iostream header file?
sorry for asking 2 much ques. at once.

Answer
I am sorry but I am not clear what you are asking when you say

   "what is the use of namespace std in c++ codes"

Do you mean the use is using declaration statements such as:

   using namespace std;

Or something else?

I shall try to explain but forgive me if I do not answer exactly what it is you really wanted to know about.

OK here goes:

ISO standard C++ introduced namespaces to C++. These allow us to partition up the naming space such that names of types, function, objects etc. do not clash between code from different sources - for example code for a specific application, the C++ standard library, third party libraries.

For example suppose that there are no namespaces and all names, including C++ standard library names, are in a single global namespace. Further suppose someone were writing an application that handled invoices or stock or some such and that this application uses a variable to hold the cost of something, however this application is written by a French person, so they use French for the names of things in their application, although without accents as the C++ character set does not include such characters. The French for cost is cout (with an circumflex - hat - over the u) so maybe some of their code look like so:

   #include <iostream>
   #include <iomanip>

   ...

   double cout( Article const & article, unsigned int quantite )   // 1
   {
       return article.Cout() * quantite;
   }
   
   int main()
   {
       Ordre ordre;
       
       // ...code to get an order to work on...
       
       Ordre::iterator i( ordre.begin() );
       Ordre::iterator fin( ordre.end() );
       double coutTotal(0.0);
       for ( ; i != fin; ++i )
       {
           Article lArticle = i->ObtenirArticle();
           unsigned int laQuantite = i->ObtenirQuantite();
           double leCout = cout(lArticle, laQuantite);             // 2
           coutTotal += leCout;

           cout << left << setw(30) << lArticle << ' '             // 3
                << right << setw(8) << lArticle.Cout() << ' '
                << setw(8) << laQuantite << ' '
                << fixed << setprecision(2) << setw(8) << leCout
                << '\n';

       }
      
       cout << right << setw(49) << "TOTAL "                       // 4
            << fixed << setprecision(2) << setw(8) << coutTotal
            << endl;
   }


OK its incomplete and not to any professional quality but will do to illustrate the point. So on the line commented as 1 a function called cout (cost) is defined and called from the line commented as 2. But oh dear the name cout is also the name of the output stream to standard console output (stdout in C terms), as is used in the lines commented 3 and 4 - how is the compiler to know the difference? Both cout names are in the same global namespace and so the name cout cannot be used for the function name  as it has already been used.

So we can get around this by placing the names in their own namespaces. So for a start the C++ standard is now in the namespace std, so we prefix all such names with std:: (the name of the namespace is std and the :: operator is the scope resolution operator used to separate parts of a name in a manner similar to using / or \  or whatever to separate parts of a file system pathname) thus:


   #include <iostream>
   #include <iomanip>

   ...

   double cout( Article const & article, unsigned int quantite )                 // 1
   {
       return article.Cout() * quantite;
   }
   
   int main()
   {
       Ordre ordre;
       
       // ...code to get an order to work on...
       
       Ordre::iterator i( ordre.begin() );
       Ordre::iterator fin( ordre.end() );
       double coutTotal(0.0);
       for ( ; i != fin; ++i )
       {
           Article lArticle = i->ObtenirArticle();
           unsigned int laQuantite = i->ObtenirQuantite();
           double leCout = cout(lArticle, laQuantite);                           // 2
           coutTotal += leCout;

           std::cout << std::left << std::setw(30) << lArticle << ' '            // 3
                     << std::right << std::setw(8) << lArticle.Cout() << ' '
                     << std::setw(8) << laQuantite << ' '
                     << std::fixed << std::setprecision(2) << std::setw(8) << leCout
                     << '\n';

       }
      
       std::cout  << std::right << std::setw(49) << "TOTAL "                     // 4
                  << std::fixed << std::setprecision(2) << std::setw(8) << coutTotal
                  << std::endl;
   }

So now we have the cout named function in the global namespace and use the C++ standard library cout from the namespace std, and the compiler can tell the difference.

Now we can tell the compiler to access all names it knows of from one namespace when looking from another using a using directive, the most common form is to make names in the std namespace visible from the global namespace so they can be used without the std:: prefix:

   #include <iostream>
   #include <iomanip>

   ...

   using namespace std;

   ...

   double cout( Article const & article, unsigned int quantite )   // 1
   {
       return article.Cout() * quantite;
   }
   
   int main()
   {
       Ordre ordre;
       
       // ...code to get an order to work on...
       
       Ordre::iterator i( ordre.begin() );
       Ordre::iterator fin( ordre.end() );
       double coutTotal(0.0);
       for ( ; i != fin; ++i )
       {
           Article lArticle = i->ObtenirArticle();
           unsigned int laQuantite = i->ObtenirQuantite();
           double leCout = cout(lArticle, laQuantite);             // 2
           coutTotal += leCout;

           cout << left << setw(30) << lArticle << ' '             // 3
                << right << setw(8) << lArticle.Cout() << ' '
                << setw(8) << laQuantite << ' '
                << fixed << setprecision(2) << setw(8) << leCout
                << '\n';

       }
      
       cout << right << setw(49) << "TOTAL "                       // 4
            << fixed << setprecision(2) << setw(8) << coutTotal
            << endl;
   }

However, of course, we find that the compiler is again confused by the two cout named items. Now however we find that we can define the cout function in the global namespace OK at line commented as 1, but the compiler cannot work out which cout to use when we try to use that name at lines qualified as 2, 3 and 4. We can specify which one is intended by prefixing the names with their namespace qualification  thus:

   #include <iostream>
   #include <iomanip>

   ...

   using namespace std;

   ...

   double cout( Article const & article, unsigned int quantite )   // 1
   {
       return article.Cout() * quantite;
   }
   
   int main()
   {
       Ordre ordre;
       
       // ...code to get an order to work on...
       
       Ordre::iterator i( ordre.begin() );
       Ordre::iterator fin( ordre.end() );
       double coutTotal(0.0);
       for ( ; i != fin; ++i )
       {
           Article lArticle = i->ObtenirArticle();
           unsigned int laQuantite = i->ObtenirQuantite();
           double leCout = ::cout(lArticle, laQuantite);           // 2
           coutTotal += leCout;

           std::cout << left << setw(30) << lArticle << ' '        // 3
                     << right << setw(8) << lArticle.Cout() << ' '
                     << setw(8) << laQuantite << ' '
                     << fixed << setprecision(2) << setw(8) << leCout
                     << '\n';

       }
      
       std::cout << right << setw(49) << "TOTAL "                  // 4
                 << fixed << setprecision(2) << setw(8) << coutTotal
                 << endl;
   }

You will notice that we just use a prefix of :: to specify the (unnamed) global namespace at the line commented as 2.

On the other hand we have probably pulled in a lot of names we are not using and probably not fully aware of, and likely to change depending on which C++ library implementation is being used. So a namespace directive such as using namespace standard is a very blunt instrument and should be used with care.

We can be more precise. We could use one or more namespace declarations which does a similar thing but for one name at a time like so:


   #include <iostream>
   #include <iomanip>

   /* ### ERATA UPDATE: Removed spurious using namespace std directive ### */

   double cout( Article const & article, unsigned int quantite )   // 1
   {
       return article.Cout() * quantite;
   }
   
   int main()
   {
       using std::left;                                            // 5
       using std::right;
       using std::setw;
       using std::fixed;
       using std::setprecision;
       using std::endl;

       Ordre ordre;
       
       // ...code to get an order to work on...
       
       Ordre::iterator i( ordre.begin() );
       Ordre::iterator fin( ordre.end() );
       double coutTotal(0.0);
       for ( ; i != fin; ++i )
       {
           Article lArticle = i->ObtenirArticle();
           unsigned int laQuantite = i->ObtenirQuantite();
           double leCout = cout(lArticle, laQuantite);             // 2
           coutTotal += leCout;

           std::cout << left << setw(30) << lArticle << ' '        // 3
                     << right << setw(8) << lArticle.Cout() << ' '
                     << setw(8) << laQuantite << ' '
                     << fixed << setprecision(2) << setw(8) << leCout
                     << '\n';

       }
      
       std::cout  << right << setw(49) << "TOTAL "                 // 4
                  << fixed << setprecision(2) << setw(8) << coutTotal
                  << endl;
   }

Here all the names from the std namespace that are unambiguous are declared at the lines starting with the line commented as 5 so they can be used without requiring the std:: qualification.

Hence we need to qualify std::cout as being in the std namespace (lines commented as 3 and 4) but we do not need to specify the global cout function using :: (line commented as 2) because std::cout is not looked for in the current,  namespace in this case or the global namespace because there is not using declaration for it and not using directive for namespace std, hence there is not ambiguity for the name cout.

That is all I am going to say on namespaces for now.

As to the input and output streams, a part of the C++ standard library is the IOStreams library. Part of the IOStreams library are the standard streams (std::cout, std::cin, std::cerr, std::clog and their wide counterparts) whose declarations are brought in by the <iostream> header. However there is more to the IOStream library than just the standard input/output stream objects. There are base class defined in the <ios> header, there are stream buffer types defined in the <streambuf> header, there is support for formatting and other manipulators (some of which I am using in the example) defined / declared in  the headers <istream>, <ostream> and <iomanip>, there are file streams defined in <fstream> and string streams in <sstream> (for std::string streams) and <strstream> (for C-string streams - depreciated feature).

If you would like to know more about namespace std and the C++ standard library then please refer to a decent C++ library text such as "The C++ Standard Library  a Tutorial and Reference" by Nicolai M. Josuttis.

For more on namespaces please refer to a decent C++ core language reference.

Anyhow hope this helps a bit.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2012 About.com, a part of The New York Times Company. All rights reserved.