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.
When you compile a C++ source code file as, for example:
the following happens:
|
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
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:
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.