Hello all:

I would be very grateful if someone could help me to understand header and definitions files.

A colleague told me that definitions should never be included in a header file, but I also read that template and inline functions should be included. Is this true? If so, is there anything else that should be defined in a header file?

If template and inline functions should be included in a header file, then should that result in class header files that contain definitions for template and inline functions, but only declarations for other functions? Or when there is a template/inline function present, or a template class, should all definitions be included in the header file?

Also, if template and inline functions should be included in a header file, doesn't this make it difficult to distribute code without giving away definitions? How do people deal with this when using templates/inlines?

Thank you for any help.

A templated function doesn't _need_ to be defined in the header file, however it is usually easier to do so (see http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file ).

Inline functions however need to be in the header file, this has to do with 'translation units'. If you have an inline declaration in 'inline.h' and it's implementation in inline.cpp and then include inline.h in A.h, the definition of the inlined function won't be available to A.h because it is in a different translation unit.

Also note, when you define a function inside a class body it is automatically inlined:

struct test {
 void returnSomething() { return 1; }    // Implicitly inlined
 inline void definedElseWhereInHeader(); // Explicitly inlined
};

// This must still be in the header file
void test::definedElseWhereInHeader() { 
  // do something
}
commented: Thanks a lot theLamb. Very helpful answer. +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.