Where to Put Class Declarations and Method Definitions

Each function that you declare for your class must have a definition. The definition is also called the function implementation. Like other functions, the definition of a class method has a function header and a function body.

The definition must be in a file that the compiler can find. Most C++ compilers want that file to end with .C, or .CPP. This book uses .CPP, but check your compiler to see what it prefers.

Many compilers assume that files ending with .C are C programs, and that C++ program files end with .CPP. You can use any extension, but .CPP will minimize confusion.


You will need to add these .CPP files to your project or makefile. How you do this will depend on your compiler. If you are using an integrated development environment, look for a command such as “add files to project.” Every .CPP file for your program must be added to the project so that it will be compiled and linked into the final executable.

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:

#include "Cat.hpp"

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 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.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151