In Java, the code for a public class (say, Foo) must be contained in a file named Foo.java. C++ does not enforce an analogous requirement; nevertheless, a similar convention is oftentimes followed, and we will follow it. We split the definition of each class between two different files: a "header" file that contains just that portion of the class definition that we are willing to expose to the world, and a separate "implementation" file that contains implementation of all other methods. In our case, this leads to Foo.h and Foo.c++. Clients of our classes will "#include" just the header file so that they are able to use the facilities of our class.

Aside: The C++ Preprocessor versus the C++ Compiler

When you compile a C++ source code file as, for example:

g++ -c Worker.c++

the following happens:

Worker.c++ preprocessor InternalFile.c++ C++ compiler Worker.o (object code)
Worker.c++ is a file typically containing "preprocessor directives"; i.e., lines whose first non-blank character is '#'.   The preprocessor performs all actions requested by those directives, eliminating those lines while creating a complete standalone source code file to send to the actual C++ compiler.      The compiler parses and generates code for the program passed to it from the preprocessor. Note in particular that the compiler is not aware of the original source code file, let alone any header files included directly or indirectly from it.   This object code file is sent to the linker to assemble the final executable program.

We introduce these ideas here mainly so that you can understand the issues surrounding the typical conventions you will see in header files. For example, you will notice the use of the following when you study Complex.h below:

#ifndef COMPLEX_H
#define COMPLEX_H
…
#endif

Example: class Complex

Among other things, the separation of the header from the implementation files in C++ code as described above necessitates the use of the C++ name scoping operator (::) when implementing the methods in the ".c++" file. Compare the following Java and C++ implementations of class Complex, an expanded version of the class introduced at the end of the Classes section:

Sneak Preview: Separate Compilation When Templates Are Involved

When using C++ template classes, care must be taken in creating header, source, and make files. There is no need to read and study those rules right this minute, but when the time comes, see these template-based rules.