Excuse me for the elementary question: In C++, should all functions be inside a class or non-global namespace? In what sort of circumstances should one write a global function?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Defining a function outside a class might be useful for operator overloading (specifically
operator<<) or perhaps a template function that allows many of your classes to be used such as:Of course, that says nothing about being inside or outside a namespace. Namespaces are useful to prevent name clashes (e.g. a function named “download” can be present in multiple libraries, so namespaces are useful in that you can use
libraryX::download ("hello")andNlib::download ("hello")in the same program whereas without a namespace the compiler would be unable to pick which function to use). However, there is nothing preventing you from making a function global by declaring the function outside of a namespace, and in fact this is quite common. If you’re creating a library, I’d recommend using a namespace to prevent another library from confusing the compiler.