Course Object Oriented Programming

Header Files

Course's Page 37 min Text by
User Image
Thiago Nepomuceno

In larger C++ projects, it is common to split the code into multiple files to improve organization, modularization, and encapsulation. Header files are a fundamental part of this structure. Below, we will explore in detail what these files are, how and why to use them, best practices for organization, and a practical example using a Movie class with interface separation (movie.hpp) and implementation (movie.cpp).

What are header files and what are they used for?

Header files in C++ (usually with .h or .hpp extensions) are files that contain declarations of program elements such as classes, functions, constants, and types. They function as an interface: they describe what exists (function signatures, class definitions, etc.) but generally do not contain detailed implementations (how these functions perform their tasks). The main function of a header file is to allow multiple source files (.cpp) to share common declarations without code duplication.

When you compile a C++ program, each .cpp file is compiled independently (each one becomes a separate compilation unit). The compiler does not know anything about the code in other .cpp files during this stage. Therefore, if a .cpp file uses a function or class defined elsewhere, it needs to know the declaration of that function or class beforehand. This is where header files come in: instead of rewriting the declarations in every source file, the declaration is placed in a header, and #include is used to insert it where needed.

Below is a simple example illustrating how to use a header file to declare a function that is implemented in another file:

sum.hpp (Function Declaration)

#ifndef SUM_HPP
#define SUM_HPP

// Declaration of the function that sums two integers
int sum(int a, int b);

#endif // SUM_HPP