Seperate compilation is the process of compiling individual files that come together to make up a bigger idea. For example, if you want to simulate a college course, you can create an indivudal teacher.cpp, student.cpp, and an overall course.cpp and their corressponding header files (or .h files) that will make up the idea of a course. We seperate each class into its own file for four main reasons: it removes clutter, the relationship between classes is more easily seen, we can divide up work among a team more easily, and it can speed up building a program. It removes clutter because every class is in their individual file so not everything is in one giant file. The relationship between classes are more easily seen because you can delegate what type of relationship each class has with each other by determing which header files are included in each .cpp file. We can divide up work among a team more easily because we can assign different team members different files to work on. And it speeds up building a program because build managers like Make, Visual Studio, and XCode can re-compile only the .cpp files that have changed since the last compilation.
The header file will just contain the method declarations for each class and each method (generally) will not have a body that shows what each method does. (We call these function prototypes.) Then in the .cpp file we will give each method a body / definition (remember to use forward declaration to show which method of which class is being defined). Note that default values are written in only the header file and the initialization list for constructors are in the .cpp file.
In your header files, make sure you are using include guards.
They compose of 3 lines:
#ifndef ...
#define ...
#endif
where you replace the "..." with the name of the header file
followed by an undercore then a h.
For example, if you have Class.h ,
the corressponding include guards
would be:
#ifndef Class_h
#define Class_h ...
#endif
The first line of code says that if Class_h
has not been defined,
define #ifndef Class_h
as the lines up to the
#endif line. Else if
the file has already been defined, go straight to
the #endif line.
It is often recommended for beginners to put every class into one file then once everything works, they should break up each class into its own file. Once you get the hang of this, slowly transition to immediately making each class their own file for each assignment.