But I'm curious, why do I have to add #include <string> to Student.h and #include <iostream> to Student.cpp, considering that these are also included in main.cpp? |
The reason for this is the way compilation works.
(I crossed out the part which doesn't match the situation in your code.)
(Note: if you included <string> in Student.h you
wouldn't have to include it in main.cpp and Student.cpp which you'll see why.)
The
compiler compiles every .cpp file
individually into what is known as
object files (they go with .o extension)
The
linker then takes all the .o files and links them into a final product that is .exe file (or an ELF binary which the equivalent if you're in GNU/Linux)
In the real world using g++ this would look like this:
1 2 3 4 5
|
//the -c option tells g++ to produce .o files.
//the -o option tells g++ to link .o files and produce a binary
g++ main.cpp -c main.o
g++ Student.cpp -c Student.o
g++ Student.o main.o -o program.exe
|
Note that each of these lines means g++ executes 3 times
separately.
For example, the first call to g++ opens the main.cpp file, processes it and produces main.o file but it doesn't even know that Student.cpp exists or that it'll be part of the main program! Therefore, if you do #include <string> in Student.cpp this is of absolutely no concern to main.cpp whatsoever.
If you put #include <string> in Student.h which is included by both main.cpp and Student.cpp then it's an entirely different story.
#include basically inserts text inside the .cpp file. g++ does this twice, once inside main.cpp and another time for Student.cpp when they are respectively compiled.
You might be confused about header guards.
As in, you may believe you need them because you're doing #include <Student.h> in both main.cpp and Student.cpp
But this is not so since they are compiled separately.
As a matter of fact, you would do just fine
without header guards here since you've only used #include <Student.h> once in each file!
The header guards are only there to prevent you to call #include <Student.h> in the
same file