Correct way to define C++ namespace methods in .cpp file
Version 2 is unclear and not easy to understand because you don't know which namespace MyClass
belongs to and it's just illogical (class function not in the same namespace?)
Version 1 is right because it shows that in the namespace, you are defining the function.
Version 3 is right also because you used the ::
scope resolution operator to refer to the MyClass::method ()
in the namespace ns1
. I prefer version 3.
See Namespaces (C++). This is the best way to do this.
C++: Namespaces -- How to use in header and source files correctly?
From a code readability standpoint, it is probably better in my opinion to use the #2 method for this reason:
You can be using
multiple namespaces at a time, and any object or function written below that line can belong to any of those namespaces (barring naming conflicts). Wrapping the whole file in a namespace
block is more explicit, and allows you to declare new functions and variables that belong to that namespace within the .cpp file as well
Is there a way to define functions declared in a namespace in a separate .h and .cpp file?
This is fine
//objectname.h
namespace ObjectName
{
Object Function(arguments);
}
You don't need function.h at all. If you want to split the namespace into several files, you would do it like:
//function.h
//includes declarations used in the function definition as well
//as possibly a redundant function declaration.
namespace ObjectName
{
Object Function(arguments);
}
In other words you need to wrap the declaration in the namespace again. (This is an advance topic. I wouldn't do it.)
Function.cpp just needs to say which function it is defining:
//function.cpp
#include "ObjectName.h"
Object ObjectName::Function(arguments)
{
....
}
Note that the statement to use a header file is #include
, not using
How do you properly use namespaces in C++?
Namespaces are packages essentially. They can be used like this:
namespace MyNamespace
{
class MyClass
{
};
}
Then in code:
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
Or, if you want to always use a specific namespace, you can do this:
using namespace MyNamespace;
MyClass* pClass = new MyClass();
Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked below, you can use as many namespaces as you like.
Proper use of namespaces for function definitions in cpp file
The problem is that your definitions:
int functionA() { return 0; }
int functionB() { return 0; }
are in the global namespace; so they declare new functions there rather than define the functions declared in namespace fun
.
The best fix is to qualify the names in the definitions:
int fun::functionA() { return 0; }
int fun::functionB() { return 0; }
This is preferable to putting the definitions inside the namespace, since it gives a compile-time check that the functions match their declarations.
C++ Namespace Functions
how should I declare namespace functions in header file?
namespace MON {
// extern:
t_ret func(const t_param& pValue);
// 'inline':
inline t_ret inline_func(const t_param& pValue) { ... }
} // << MON
Should header only contain function definitions like class header file and implementations should be in cpp file, or should I straight away implement functions in header file?
that depends on whether you want them (potentially) inlined or exported. this often comes down to minimizing dependencies.
to expand on exporting or inlining:
you'd often favor an extern function to minimize dependencies in c++. this is equivalent to separating the definition from the declaration in a class method:
file.hpp
namespace MON {
// extern:
t_ret func(const t_param& pValue);
} // << MON
file.cpp
#include "hefty_stuff.hpp"
MON::t_ret MON::func(const t_param& pValue) { ... }
however, it's at times critical for the definition to be visible in some cases, often for performance or when you know size is important and the header is not included many places. thus, the inline
variant is also an option.
an inline function may still be exported, and it may be inlined as requested -- however, any inline function copies may be merged (specifically, the implementation is free to assume all definitions are equal and any copies of the function are unnecessary).
with exported definitions, you may selectively restrict (or quarantine) your include dependencies. that is, #include "hefty_stuff.hpp"
need not be in the header to use the functions in file.hpp
.
Basically, I am trying to implement an application to parse a text file that contains some commands. So I am thinking of implementing static helper methods to handle text processing.
well, static
should be avoided here. c++ uses the one-definition-rule. static
will just result in a lot of unnecessary copies. furthermore, an anonymous namespace is the c++ approach to c's static
function:
namespace {
t_ret func(const t_param& pValue) { ... }
} // << anon
note: anonymous namespaces may also result in unnecessary copies. the reason you would use them as a substitute for a static function is if you want or need to deviate from the one-definition-rule, and do not want to declare the symbol in a scope which may be 'resolved'.
the final point regards template<>
declarations. with templates, the definition must be visible where used, unless your compiler supports extern templates. for templates, you can accomplish definition visibility in multiple ways. typically, people will simply declare the definition in place, or add a header for the definitions which is included either at the end of the header or as needed. with templates, functions do not need to be declared inline
to avoid multiple definition errors.
Related Topics
Understanding Gsl::Narrow Implementation
Boost::Spirit::Qi Parser: Index of Parsed Element
Finding the Max Value in a Map
What Is Vc++ Doing When Packing Bitfields
Strange Behavior with Constexpr Static Member Variable
Outputting More Things Than a Polymorphic Text Archive
What Does "-Wall" in "G++ -Wall Test.Cpp -O Test" Do
When Does a Std::Vector Reallocate Its Memory Array
How Does Calling Srand More Than Once Affect the Quality of Randomness
C++: Timing in Linux (Using Clock()) Is Out of Sync (Due to Openmp)
What Are the Incompatible Differences Between C(99) and C++(11)
How to Guarantee Fast Shutdown of My Win32 App
Array of Size Defined by Not Constant Variable