|
|
|
|
|
|
|
Put Class Declarations in Header Files |
|
|
|
|
|
|
|
|
Although you are free to put the declaration in the source code file, it 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, I put the declaration of the Cat class into a file named CAT.HPP, and I put the definition of the class methods into a file called CAT.CPP. I then incorporate the header file into the .CPP file by putting the following code at the top of CAT.CPP: |
|
|
|
|
|
|
|
|
This tells the compiler to read CAT.HPP into the file, just as if I had typed its contents into the file at this point. Why bother separating them if you're just going to read them back in? Most of the time, clients of your class don't care about the implementation specifics. Reading the header file tells them everything they need to know; they can ignore the implementation files. |
|
|
|
|
|
|
|
|
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 interface is usually stored in an .HPP file, which is referred to as a header file. |
|
|
|
| | The function definition tells the compiler how the function works. The function definition is called the implementation of the class method, and it is kept in a .CPP file. The implementation details of the class are of concern only to the author of the class. Clients of the classthat is, the parts of the program that use the classdon't need to know (and don't care) how the functions are implemented. |
|
|
|
|
|
Just as you can ask the compiler to make a regular function inline, you can make class methods inline. The keyword inline appears before the return value. The inline implementation of the GetWeight() function, for example, looks like this: |
|
|
|
|
|
|
|
|
inline int Cat::GetWeight()
{
return itsWeight; // return the Weight data member
} |
|
|
|
|
|