CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 32
  1. #1
    Join Date
    May 2018
    Posts
    158

    using namespace std

    I didn't understand in what file I have to recall using namespace std; statements.

    My C++ project contains:

    main.cpp
    app.cpp
    app.h

    in app.h I defined class and some constants.
    Can I define using namespace std; in the only app.h and recall #include "app.h" inside both main.cpp and app.cpp ?
    In this way using namespace std; is how if It's was written in both files?
    Thanks

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: using namespace std

    You don't have to use using directives like using namespace std at all, e.g., you could fully qualify the names, e.g., instead of cout write std::cout. If you do want to use them, then the idea is to make it such that it is obvious that they are in effect, e.g., you could place them at function scope (so they will only be in effect in that scope and hence would be glaringly obvious), or at file scope (after the header inclusions) in a file that is not intended to be included in other files (hence you would not place them at file scope in a header file).
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    May 2018
    Posts
    158

    Re: using namespace std

    Thanks for your suggestions but my examples for exercises provide always these statements so I need to know how to use it into main.cpp, app.h and app.cpp
    It's necessary to use this directive on all files ?! Or only in app.h and recall it inside .cpp files ?

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: using namespace std

    Quote Originally Posted by zio_mangrovia
    Thanks for your suggestions but my examples for exercises provide always these statements so I need to know how to use it into main.cpp, app.h and app.cpp
    Examples are just examples. They can help you to gain in understanding, but you don't have to copy them once you understand what the things they do are about. The point is, you need to understand that a using directive for the std namespace means that for the scope in which the directive is in effect, you can skip qualifying the names in the std namespace, hence instead of writing std::cout you can just write cout. The examples you have seen tend to do this presumably because they use names from the std namespace quite a bit, so it is more convenient to have a single using directive instead of always qualifying the names with the namespace name.

    Quote Originally Posted by zio_mangrovia
    It's necessary to use this directive on all files ?!
    No.

    Quote Originally Posted by zio_mangrovia
    Or only in app.h and recall it inside .cpp files ?
    It seems that you didn't read my previous post: "If you do want to use them, then the idea is to make it such that it is obvious that they are in effect, e.g., you could place them at function scope (so they will only be in effect in that scope and hence would be glaringly obvious), or at file scope (after the header inclusions) in a file that is not intended to be included in other files (hence you would not place them at file scope in a header file)."

    Is app.h a header file? Are main.cpp and app.cpp meant to be included in other files?
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    Aug 2006
    Posts
    231

    Re: using namespace std

    Adding "using namespace" to a scope means that names/symbols in the specified namespace will be available for lookup in that scope.

    If you do that at global scope in a header file, it means that these names are "visible" to the compiler in all files that include that header file.

    This can cause problems if you have names in your code that also exist in the used namespace.

    In your case the namespace is std, which is the standard library namespace. Beware that we don't know what names will be added to it later, so a future version of it may add new names that can break your code, or potentially change the behaviour, if you have used such names.

    So, if you're going to use the "using namespace" directive, you should try to limit its scope.

    I suggest that you explicitly write "std::" in front of any standard library names that appear in your header file. If it's a requirement of the exercise to write "using namespace std", put it after all include directives in each cpp file that use the standard library.
    Last edited by TubularX; June 9th, 2018 at 04:52 AM.

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: using namespace std

    You don't say how you are learning c++. c++ is a large and complex language and until you are fairly familiar with it, when learning you just need to know that some stuff you just put in the code 'to make it work' and that later you'll understand this and know why, when, how etc.

    For further info see
    http://www.learncpp.com/cpp-tutorial...ng-statements/
    http://www.learncpp.com/cpp-tutorial/19-header-files/
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    May 2018
    Posts
    158

    Re: using namespace std

    Thanks, I read this document. Good step to start.

  8. #8
    Join Date
    May 2018
    Posts
    158

    Re: using namespace std

    I understood all your best practices but I think It's necessary to show example which is written by an Italian University.
    I should to make similar exercises so it's primary target to follow this method.

    compito.h
    Code:
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    const int DIM = 3;
    struct elem{
      int info;
      elem* pun;
    };
    
    class Schedario{
      
      elem* p0[DIM];
      void svuota(elem*&);
      Schedario(const Schedario&);  
      Schedario& operator=(const Schedario&);
    public:
      Schedario();    
      void aggiungi(int, int);
      Schedario& operator-=(int);
      friend ostream& operator<<(ostream&, const Schedario&);
      void promuovi(int,int);  //  7pt
      ~Schedario();            //  3pt
    };

    main.cpp
    Code:
    #include <iostream>
    using namespace std;
    #include "compito.h"
    
    int main(){
      {
        cout<<"--- PRIMA PARTE ---" << endl;
        cout << "\nTest del costruttore e dell'operatore di uscita" << endl;
        Schedario s;
        cout << s << endl;
        
        cout << "\nTest della aggiungi" << endl;
        s.aggiungi(3, 12);
        s.aggiungi(3, 10);
        s.aggiungi(2, 21);
        s.aggiungi(2, 48);
        s.aggiungi(2, 35);    
        s.aggiungi(1, 6);  
        cout << s << endl;
    
        cout << "\nTest dell'operatore -=" << endl;
        s-=2;
        cout << s << endl;
                
      
        cout << "\n--- SECONDA PARTE ---" << endl;
              
        s.aggiungi(2, 5);
        s.aggiungi(2, 3);    
        s.aggiungi(2, 5);
        s.aggiungi(2, 5);       
        s.aggiungi(2, 8);
        s.aggiungi(2, 5);
        
        cout <<"\nTest della promuovi"<<endl;
        cout << "  [s prima della promuovi]" << endl;
        cout << s << endl;
        s.promuovi(2,5);    
        cout << "  [s dopo la promuovi]" << endl;
        cout << s << endl;
      }
      cout << "\nTest del distruttore (s e' stato appena distrutto)\n" << endl;     
      return 0;
    }

    compito.cpp
    Code:
    #include "compito.h"
    
    // funzione di utilita'
    void Schedario::svuota(elem*&p){  
      while( p != NULL ){
        elem*r = p;
        p = p->pun;
        delete r;
      }
    }
    
    // --- PRIMA PARTE ---
    Schedario::Schedario(){
      for (int i = 0; i < DIM; i++)
        p0[i] = NULL;
    }
    
    ostream& operator<<(ostream& os, const Schedario& p){  
      for(int i = 0; i < DIM; i++){
        elem* q;
        os << 'L'<<i+1<<'(';
        for( q = p.p0[i]; q != NULL; q = q->pun)
          if (q->pun != NULL)
            os << q->info<<',';
          else
            os << q->info<<')';
        if ( q == p.p0[i] )
          os << ')';
      }
      return os;
    }
    
    void Schedario::aggiungi(int liv, int tip){
      if ( liv >= 1 && liv <= DIM ) {
        elem* r = new elem;
        r->info = tip;
        r->pun = p0[liv-1];
        p0[liv-1] = r;
        }
    }
      
    Schedario& Schedario::operator-=(int liv){
      if ( liv >= 1 && liv <= DIM )
        svuota(p0[liv-1]);
      return *this;
    }
    
    
    // --- SECONDA PARTE ---  
    void Schedario::promuovi(int liv, int tip){
      if ( liv < 1 || liv > 2 )
        return;
                   
      elem* q = p0[liv-1];
      elem* prec; 
      while (q!= NULL) {
        if (q->info == tip) {
          if(q == p0[liv-1]) { // elemento in testa di p0[liv-1]
             p0[liv-1] = p0[liv-1]->pun;                       
             //  sposto elem puntato da q in testa nella lista p0[liv]
             q->pun = p0[liv];
             p0[liv] = q;
             // aggiorno q in  p0[liv-1]
             q = p0[liv-1];                 
          }
          else{ // elemento in  mezzo/fondo di p0[liv-1]
            prec->pun = q->pun ; 
            //  sposto elem puntato da q in testa nella lista p0[liv]
            q->pun = p0[liv];
            p0[liv] = q;
            // aggiorno q in  p0[liv-1]
            q = prec->pun;
          }                 
        }
        // scorro la lista  p0[liv-1]  
        else {
          prec = q;
          q = q->pun;             
        }
      }// fine while
    }
    
    Schedario::~Schedario(){
      for (int i = 0; i < DIM; i++)
        svuota(p0[i]);
    }
    I hope this example can expose my doubts.
    I understand the using namespace std is necessary inside main.cpp because cout is used.
    I don't understand because using namespace std is used into compito.h because this header file contains only forward declarations so no standard function is called; standard library functions are invoked into compito.cpp hence what means to insert using namespace std inside header file?

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: using namespace std

    compito.h should be

    Code:
    #include <iostream>
    
    const int DIM = 3;
    struct elem{
      int info;
      elem* pun;
    };
    
    class Schedario{
      
      elem* p0[DIM];
      void svuota(elem*&);
      Schedario(const Schedario&);  
      Schedario& operator=(const Schedario&);
    public:
      Schedario();    
      void aggiungi(int, int);
      Schedario& operator-=(int);
      friend std::ostream& operator<<(std::ostream&, const Schedario&);
      void promuovi(int,int);  //  7pt
      ~Schedario();            //  3pt
    };
    compito.cpp then starts with

    Code:
    #include <iostream>
    #include <cstring>
    #include "compito.h"
    using namespace std;
    
    // funzione di utilita'
    void Schedario::svuota(elem*&p){  
    ...
    and main.cpp is fine (although using ... usually comes after the includes).
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  10. #10
    VictorN's Avatar
    VictorN is online now Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: using namespace std

    Quote Originally Posted by zio_mangrovia View Post
    I hope this example can expose my doubts.
    I understand the using namespace std is necessary inside main.cpp because cout is used.
    I don't understand because using namespace std is used into compito.h because this header file contains only forward declarations so no standard function is called; standard library functions are invoked into compito.cpp hence what means to insert using namespace std inside header file?
    This code should be changed to look like:
    compito.h
    Code:
    #include <iostream>
    #include <cstring>
    // using namespace std; - it should be removed!
    
    const int DIM = 3;
    ...
    };

    main.cpp
    Code:
    #include <iostream>
    
    #include "compito.h"
    using namespace std;  // this directive should be after the latest #include
    
    int main(){
          ...
    }

    compito.cpp
    Code:
    #include "compito.h"
    using namespace std; 
    
    // funzione di utilita'
    ...
    }
    Victor Nijegorodov

  11. #11
    Join Date
    May 2018
    Posts
    158

    Re: using namespace std

    OK, you correct me if I make mistake but using namespace std is not necessary in compito.h because there is no standard function but only forward declarations and a class.
    If It my opinion is right, I ask myself because #include iostream and cstring are necessary into header file if, even in this case, apper only forward declarations, e.g. no cout is shown.
    thanks

  12. #12
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: using namespace std

    using namespace std was in the original compito.h because compito.h uses ostream from <iostream>. It's not good practice to have using ... in a header file so ostream becomes std:: ostream as per post #9

    You put the necessary #includes in the file (.h or .cpp) as are needed for what that file requires.
    You don't use using... in a header file.

    It doesn't matter if an #include is included more than once in any compilation unit (ie a .cpp file), that is fine.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  13. #13
    Join Date
    May 2018
    Posts
    158

    Re: using namespace std

    Quote Originally Posted by 2kaud
    using namespace std was in the original compito.h because compito.h uses ostream from <iostream>.
    about cstring library? In compito.h, what function does it require this library?



    You don't use using... in a header file.
    Ok, very clear

    It doesn't matter if an #include is included more than once in any compilation unit (ie a .cpp file), that is fine.
    Excuse me, but I didn't understand this one and I need some assurances.

    If these conditions are verified:

    • compito.h contains both #include <iostream> and #include <cstring>
    • both main.cpp and compito.cpp contain #include "compito.h"
    • compiler copies compito.h into both main.cpp and compito.cpp

    hence in this way is how if I had written #include <iostream> and #include <cstring> directly inside these 2 .cpp files ?
    So I save 2 code lines in every .cpp file?

    thanks
    Last edited by zio_mangrovia; June 9th, 2018 at 12:07 PM.

  14. #14
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: using namespace std

    about cstring library? In compito.h, what function does it require this library?
    It doesn't.

    hence in this way is how if I had written #include <iostream> and #include <cstring> directly inside these 2 .cpp files ?
    So I save 2 code lines in every .cpp file?
    Yes, but don't. You shouldn't assume that a particular #include also includes another #include. Put the required #includes in the .h and .cpp files. The exception to this is when you start to use pre-compiled headers (but that's probably for later). The documentation for a particular function/class will say what header file to include - so just include it. It doesn't make your .exe file any larger or slower if header files are included more than once - they are designed so that they can be.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  15. #15
    Join Date
    May 2018
    Posts
    158

    Re: using namespace std

    Quote Originally Posted by 2kaud View Post
    You shouldn't assume that a particular #include also includes another #include. Put the required #includes in the .h and .cpp files.
    according to view of the above, compito.cpp includes cstring library, perhaps because It defines NULL pointer? I see any string functions as strcmp, strlen,...
    Why VictorN has written include directives different from yours?
    Last edited by zio_mangrovia; June 10th, 2018 at 01:49 AM.

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured