Header Files for templates and structures

I was reading and chanced upon these terms.

I understand that header files should only include:
1. Function Prototypes
2. Symbolic Constants
3. Structure/Template/Class declarations
4. Inline functions

However, I don't understand point 3 and 4.

For example if I've a structure.
1
2
3
4
  struct x
  {
      int y;
  };


As for template
1
2
3
template <typename>
void z (int)
{...};


Are these declarations or definitions? Some websites mix both terms up that confuses me.

And why does inline function work? I know it replaces the function with the code than to do a "copy". But isn't it a definition?

Thank you!
Last edited on
Point 3 should have said definitions instead of declarations.

A declaration tells the compiler that there is something with that name and what type it has.
1
2
3
// Declarations:
struct x; // There is a struct named x.
void foo(int); // There is a function named foo that returns nothing and takes a single int as argument. 

A definition tells the compiler what something is.
1
2
3
4
5
6
7
8
9
// Definitions:
struct x
{
	int y;
};
void foo(int value)
{
	std::cout << value;
}

A definition gives the compiler the same information (and some more) as a declaration (name, type) so a definition is always also a declaration. You can have as many declarations as you want in your program, but multiple definitions are often not allowed, at least not in the same file (or translation unit).

Inline functions are a bit different than normal functions in that you are allowed to define them once for each translation unit instead of only once in your whole program. I think it has to do with the way C++ is compiled. Each .cpp together with all header files it includes (this is what's called a translation unit) is compiled in separation without the knowledge of other .cpp files. To be able to actually perform inlining (injecting the code of the function where it's called) the compiler need to have the code for that function available so I guess they just made an exception for that reason.
Last edited on
As long as no memory is created it can be included in the header file?

I went to google and concluded that as long as the header file doesn't include stuff that create storages it can be included in the header file?
Topic archived. No new replies allowed.