As a beginner, I am finding it difficult to understand the function of header files, why they are used, and what you should include in them. I don't really know the difference between a .h file and a .cpp file.
Suppose I have a class MyClass, with a member variable, int MyVariable, and a member function MyFunction. I could write this in a .h file:
And if I #include this .h file at the beginning of my source code, then I can use this class with no problems.
// Do something
However, I have noticed that many projects will only put the decleration in the .h file, and the definition will appear in a .cpp file. What is the point in this? As far as I'm concerned, it just makes everything more dispersed and harder to follow.
Other times, the definition is included in the .h file, as above, and this seems like the sensible way of going about it.
Perhaps it is something to do with how the compiler interprets .h and .cpp files, but I don't really know what the difference is between them.
Please help :)
when you want to use std::string are you interested to know how the c_str() function implemented?
no - enogh to know that it is present and its prototype.
headers contain info required to use the class from the external code - class definition and function prototypes.
all the code that could be hidden from the user of the class and (for exaple) compiled in the lib-file provided with the header file to use on linkage stage - goes into cpp
While it will work with classes, it also does two things:
It implies that all functions are inline.
By storing the definition along with the declaration, you make it harder to browse the contents of the class, what members it exposes, etc.
Aside from that, headers are used to keep declarations that the compiler needs to see when you want to use something - ie a class declaration. So that when you use the class, you simply include the file instead of re-writing the class declaration.