
Keith B. answered 09/20/19
Software Engineer and Math Geek
C++ is a strongly typed language, meaning that you must define functions and classes before you can use them. When you are working on a small project, this isn't a much of an issue, as you can write your functions before you use them or place their prototype in your file prior to where the function is called. The same goes for classes; you have to lay them out before you can use them, or use a forward declaration indicating that a definition exists for the function for the compiler to find.
As your project grows, this gets harder and hard to maintain. Tens of lines become hundreds of lines becomes thousands or larger - I've worked on projects with over 1 million lines of code. Imagine having all of that in one file. Instead, C++ allows you to place code in a separate file, compile it to object code and then link all the files together to produce the executable.
The advantages to this is several fold. First, you can organize the separate files, typically by placing the class definition in a .h (or .hpp) file and the methods in a like named .cpp. These files can also be further organized into separate folders. Next, with the separate files, a utility called make can keep track of the files that have changed (say you made an edit in a few different files) and only recompile those that changed. If you have a project with hundreds of files (not unheard of), only compiling those that changed and then linking saves a LOT of time. I've worked on projects where a full rebuild requires running it overnight, whereas a recompile of what's changed may take all of five minutes.
With your files organized now as such (one class to a file), the rules about typing still exist - the compiler still needs to know the prototype of a function or the definition of a class, even if it's in another file. By adding the include (#include "MyClass.h") you can provide this information. The actual class and functions need only be there when the link operation is performed as the last step.
Lastly, not all code goes to an executable; instead, you can build libraries. These are a collection of your code, compiled down and ready to be linked to and re-used. Say, for example, you've created a great library for printing reports. On your next project, rather than re-creating a whole new collection of classes, you can just reuse the library from a previous project. Re-use is an important part of coding.
But wait, there's more! Those same libraries can be released to the public. You can allow other people to use your library, and by providing them the include and the library, they don't need to know how your code does what it does (encapsulation), but by having the includes they know how to interface with it. You're already probably using some -- #include <iostream> for example, is the standard input/output library. You've probably not stopped to think about how cin and cout works, but you use them all the same.