Sign in to follow this  

cpp file vs .h file

This topic is 4305 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
"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. :)

Share this post


Link to post
Share on other sites
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"

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4305 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this