I want to start to prefer free (non-member) functions over member functions - following this article http://www.drdobbs.com/184401197
I am used to organize my C++ classes in that way, that I have ClassName.h
for the declaration and a ClassName.C
for the implementation.
ClassName.h :
struct ClassName {
ClassName();
void setData( unsigned data );
};
and the implementation is then
ClassName.C :
#include "ClassName.h"
ClassName::ClassName() { dosomething(); };
void setData( unsigned data ) { dootherthings(); };
So how do I organize my code when I want have a free function adjustClassData()
?
I also want to put this function into namespace.
Assuming ClassName
is in namespace foo
, then I would put the free function into namespace foo
as well:
namespace foo {
void adjustClassData( ClassName & inObj );
}
I am looking for the aspects of namespace
and suggestions for file names.
I am looking for some best-practices - as there is no C++ rule in the standard prescribing the file organization.
When a programmer types a sequence of C programming language statements into Windows Notepad, for example, and saves the sequence as a text file, the text file is said to contain the source code. Source code and object code are sometimes referred to as the "before" and "after" versions of a compiled computer program.
Every C program has a primary function that must be named main . The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.
You could put the free functions that deal with a particular class in the class header and implementation file if there are not too many.
Otherwise, come up with a naming convention and put them in a separate header and implementation file (e.g ClassNameFunctions.h/.cpp).
If you're looking to replace member functions with free functions, I'm assuming these free functions are tightly related to the class in question. In which case, they shouldn't be public. I'd go with anonymous inner namespaces:
//myclass.h
namespace myNamespace
{
class MyClass
{
void foo();
};
}
//myclass.cpp
#include "myclass.h"
namespace myNamespace
{
namespace
{
void helper() {};
}
void MyClass::foo()
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With