Usually, in headers goes the declarations and in source files goes the implementation. Though there is a exception for this in case of templates. Remember that only source files get compiled. So, what ever symbols present in the source file must be known to the compiler. Now taking an example -
foo.h
struct foo
{
int number ;
foo( int x );
};
foo.cpp
Now, there is a method that is unimplemented in struct foo
i.e., constructor. If you need to implement that in a seperate source file, you need to #include "foo.h"
. With out it, if you just go on implementing it's methods, compiler doesn't know what is "foo".
#include "foo.h"
foo::foo( int x )
{
number = x; // This can be achieved through initializer lists too.
}
Before even the compiler stage, preprocessor copies the contents of foo.h
to foo.cpp
. After preprocessing, the original foo.cpp
turns to be -
struct foo
{
int number ;
foo( int x );
};
foo::foo( int x )
{
number = x; // This can be achieved through initializer lists too.
}
Now, every method/symbol that is being defined/used in the source file is known to the compiler to which it belogs to. And in general, the corresponding source file of x.h
will be x.cpp
. Also know that, every source file passes these stages to give a final executable. ( PreProcessor -> Compiler -> Linker ). Hope it helps to an extent.