Why do we declare functions in the header file?

So I’m currently on lecture 59 of the Unreal course and I’m curious as to why we declare functions in the header file.

For example, when you define your EndGame function, you put it in the header then reference the name in the BullCowCartridge file, but then you write all the code of the function in the file. In my head, it makes more sense to have the function code in the header instead. Maybe I have a misunderstanding of what the header file does, so I would love an explanation.

Thanks everyone!

The best way to think of the header file is it is a template or definition of the class with their methods, structs and functions.

When you include a header using #include the compiler is then made aware of the definitions and takes them as correct. This method hasn’t really changed since the days of K&R C from the 1970s which required you to define your functions before they are used or forward-declare them. This is why the headers don’t generate the errors when the calls to the methods or functions don’t match the definition in the headers - it’s the actual CPP file that has the error. The headers themselves actually facilitate the use of multiple files for your code so when you need to identify available methods/functions to the code file, you don’t have to forward declare each method you use, just include.

For languages that don’t take this approach, code has to be searched for the function to ensure the calls match the declaration and so it takes a lot longer to compile code.

So, C/C++ uses #include to ensure when a function/method is used, the parameters match what is expected of it.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms