Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ source code organization for free functions

Tags:

c++

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.

like image 535
Carsten Greiner Avatar asked Jun 05 '12 19:06

Carsten Greiner


People also ask

What is source file in C?

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.

What is the main function in C?

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.


2 Answers

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).

like image 115
Anon Mail Avatar answered Sep 30 '22 06:09

Anon Mail


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()
   {
   }
}
like image 38
Luchian Grigore Avatar answered Sep 30 '22 06:09

Luchian Grigore