Sams Teach Yourself C++ in 21 Days

(singke) #1
You are free to put the declaration in this file as well, but that is not good programming
practice. The convention that most programmers adopt is to put the declaration into what
is called a header file, usually with the same name but ending in.h,.hp, or .hpp. This
book names the header files with .hpp, but check your compiler to see what it prefers.
For example, you put the declaration of the Catclass into a file named Cat.hpp, and you
put the definition of the class methods into a file called Cat.cpp. You then attach the
header file to the .cppfile by putting the following code at the top of Cat.cpp:
#include “Cat.hpp”
This tells the compiler to read Cat.hppinto the file, the same as if you had typed in its
contents at this point. Be aware that some compilers insist that the capitalization agree
between your #includestatement and your file system.
Why bother separating the contents of your .hppfile and your .cppfile if you’re just
going to read the .hppfile back into the .cppfile? Most of the time, clients of your class
don’t care about the implementation specifics. Reading the header file tells them every-
thing they need to know; they can ignore the implementation files. In addition, you might
very well end up including the .hppfile into more than one .cppfile.

162 Day 6


The declaration of a class tells the compiler what the class is, what data it
holds, and what functions it has. The declaration of the class is called its
interface because it tells the user how to interact with the class. The inter-
face is usually stored in an .hppfile, which is referred to as a header file.
The function definition tells the compiler how the function works. The func-
tion definition is called the implementation of the class method, and it is
kept in a .cppfile. The implementation details of the class are of concern
only to the author of the class. Clients of the class—that is, the parts of the
program that use the class—don’t need to know, and don’t care, how the
functions are implemented.

NOTE

Inline Implementation..........................................................................................


Just as you can ask the compiler to make a regular function inline, you can make class
methods inline. The keyword inlineappears before the return type. The inline imple-
mentation of the GetWeight()function, for example, looks like this:
inline int Cat::GetWeight()
{
return itsWeight; // return the Weight data member
}
Free download pdf