Quantcast
Channel: HashFold » CPP
Viewing all articles
Browse latest Browse all 5

CPP Header Files

$
0
0

The standard practice is to have one header file (.h) per class file (.cpp). The correct use of the header files could enhance the readability and also boost the performance of the code. When deciding which portion of code to put where , think about the Locality of Reference first because this matters as well.

Below are the few points to remember while designing the header files:

1. Header file guard

All header files should be guarded well to avoid multiple inclusions in the code. e.g.


#ifndef MY_SAMPLE_HEADER_H

#define MY_SAMPLE_HEADER_H

//contents of the header file here...

#endif

2. Header file depedencies

Any file including the header files needed to be recompiled whenever the contents in the header file changes. This leads to big dependency in the compile time. In the scenarios where including header file is not needed, forward declaring the class should be more than enough. Doing this will help not recompile the class however the symbol will be resolved at the linking phase of the compilation process.

3. Inline methods

Inline methods are defined in side the class declaration body itself i.e. in .h file instead of the .cpp file. Inlining methods which are about 10 lines big lead to better program performance.

4. Method parameter and Include file ordering

The general convention to order the parameters in the methods are input first and then output parameters. Remember that all inputs should be declared “const <data type> &_data” so that method can’t modify the _data.
The output parameters are generally declared non-constant “<data_type> &_data”.

The order of the header file included should be done in the order of their path names. This doesn’t made any difference in the performance of the program however it improves the readability of the code.

5. Header comment

Header comments give the glimpse of what is file about and how the code has evolved since its first version.

a sample of the comment is here:

/* ---------------------------------------------------------------------------
**
** <filename>.h
** Description:<very brief file description>
**
** Author: <original author>
** Change History
** 1.0 - changed the accessors to inline
** -------------------------------------------------------------------------*/

Viewing all articles
Browse latest Browse all 5

Trending Articles