Programming Tutorials

Where to Put Class Declarations and Method Definitions in C++

By: Ivan Lim in C++ Tutorials on 2007-09-09  

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.

 


NOTE: 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 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 Cat class 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 .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 you had typed in its contents 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.

 


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





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)