I have always seen people write
class.h
#ifndef CLASS_H
#define CLASS_H
//blah blah blah
#endif
The question is, why don\'t they
It doesn't - at least during the compilation phase.
The translation of a c++ program from source code to machine code is performed in three phases:
class.h
is inserted in place of the line #include "class.h
. Since you might be includein your header file in several places, the #ifndef
clauses avoid duplicate declaration-errors, since the preprocessor directive is undefined only the first time the header file is included.In summary, the declarations can be shared through a header file, while the mapping of declarations to definitions is done by the linker.
.cpp
files are not included (using #include
) into other files. Therefore they don't need include guarding. Main.cpp
will know the names and signatures of the class that you have implemented in class.cpp
only because you have specified all that in class.h
- this is the purpose of a header file. (It is up to you to make sure that class.h
accurately describes the code you implement in class.cpp
.) The executable code in class.cpp
will be made available to the executable code in main.cpp
thanks to the efforts of the linker.
That's done for header files so that the contents only appear once in each preprocessed source file, even if it's included more than once (usually because it's included from other header files). The first time it's included, the symbol CLASS_H
(known as an include guard) hasn't been defined yet, so all the contents of the file are included. Doing this defines the symbol, so if it's included again, the contents of the file (inside the #ifndef
/#endif
block) are skipped.
There's no need to do this for the source file itself since (normally) that's not included by any other files.
For your last question, class.h
should contain the definition of the class, and declarations of all its members, associated functions, and whatever else, so that any file that includes it has enough information to use the class. The implementations of the functions can go in a separate source file; you only need the declarations to call them.