c++classpointersforward-declaration

May I #include in .hpp files?


I have a class called A, which has its .cpp and .hpp files. It depends on classes B and C. Now, I'm wondering, should I #include B.hpp and #include C.hpp in A.cpp or A.hpp? I think it would be beneficial for me to #include in the A.hpp file, because I'm creating a vector of B*'s, and I'm not sure that the compiler will know the correct size of B if I only forward declare it (so I couldn't pointer increment correctly)... By "forward declaration", I mean writing class B; and class C; in the beggining of A.hpp.


Solution

  • As already mentioned, you can often work-around having to #include stuff by using forward declarations, and indeed the best practice is to minimize the amount of other headers included.

    But: To answer your questions headline: yes you may, and the common mechanism to avoid "circular inclusion" is the following

    A.hpp:

    #ifndef A_HPP_INCLUDED
    #define A_HPP_INCLUDED
    
    ... // code
    
    #endif
    

    Now if say B.hpp includes A.hpp, and subsequently, C.hpp looks like:

    #ifndef C_HPP_INCLUDED
    #define C_HPP_INCLUDED
    
    #include "A.hpp"
    #include "B.hpp"
    
    ...
    #endif
    

    Then you won't get an error stating that e.g. 'class A' has already been defined.