cpp file vs .h file

Started by
3 comments, last by Roboguy 18 years, 1 month ago
I can't seem to find a difference between the following: 1. Making a class in a .h file and then including it in your main .cpp 2. Making a class in a new .cpp file, and then adding it to your project. What is the difference, and what are the advantages?
Mitchen Games
Advertisement
"Making a class" is a bit unclear. Are you just prototyping the class and its member functions, or are you actually including the source to the functions along with it?

Normally one would prototype the class in a header and put the source to the member functions in a separate .cpp file (or files). Then the main.cpp simply includes the header.

If you put the source in a header and include it from multiple source files, the linker will complain from multiply defined symbols. If you only have just one source file, including everything will work, but your compiler will hate you. :)
hpp or h are for definitions of variables and objects and the cpp or c are used to actually implement the code that the hpp has set up. Its also good for allowing other cpp files to use the same objects and definitions.

hpp can contain code as well but its more common to have one hpp for the declaring and one cpp for the implementations of what is in the hpp file.

header files exist for 1 main reason and that is to include things used in multiple c and cpp files more than once without redeclairing things which would be bad.

Also you can't #include "something.cpp"

its #include "something.hpp"
Quote:Original post by DreamGhostAlso you can't #include "something.cpp"


[aside] Actually there is one place you might use that: in a header that defines a template. Instead of including the .h in the .cpp, you include the .cpp in the .h. It's mostly cosmetic, but it is feasible.
Quote:Original post by DreamGhost
Also you can't #include "something.cpp"


You can #include a file with any extension.

This topic is closed to new replies.

Advertisement