Where should I include other header files, in header file or source file? What is the difference between the below two:

Example:

//file1.h
#include "file2.h"
...

OR

//file1.h
class class2;
...
//file1.cpp
#include "file2.h"
...

both of them...
ex:

//-------------- <file1.h> -----------------//
#include <iostream> //..header file
class CClass
{
        //...
        void funct(std::string &str);
};
//-------------- </file1.h> -----------------//

//-------------- <file1.cpp> -----------------//
#include "file1.h" // header file
//#include <...h>
void CClass::funct(std::string &str)
{
       //...
}
//...
//-------------- </file1.cpp> -----------------//

//-------------- <main_source_file> -----------------//
#include "file1.h" // header file

int main()
{
      CClass c_class;
      //...
      return 0;
}
//-------------- </main_source_file> -----------------//

Then which version is better? Or at least preferred? Does the first version (may) have bad consequences?

If the content of header A relies on content of header B, then it is generally a good idea for header A to #include header B. Examples of "relies on" are;

- header B declares a base class, and a class in header A inherits from it.
- header B defines a type (eg classes, enums, typedefs) and any function in header A accepts arguments or returns that type.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.