Important: Please read the Qt Code of Conduct -

Class implementation in header file

  • Hello,

    Am writing an app with several classes and the structure is pretty hard to get. So i find myself having to put one of the class implementations together with the declaration in the header file so as to remove the cpp file for a less complex #include structure. But is this practice healthy for the application?
    Thanks in advance

  • Common practice is: Have each class' implementation in a separate source (.cpp) file and have the class' declaration in a separate header (h.) file. Thus, for a class CMyClass you'd have "MyClass.cpp" plus "MyClass.h".

    You should think of the class' header file as its "public" interface, i.e. that is what other must neccessarily include to use the class - but not more! Therefore you should keep the header file as clean as possible to avoid dependency nightmare! You should avoid any #include directives in a header file, unless absolutely necessary. Most of the time, you can move the #include into the source (.cpp) file and use a forward declaration in the header file.

    Finally, I'd avoid putting two or more class declarations into the same header (.h) file, unless these two classes are always used together anyway.

    @/* ---- MyClass.h ---- */

    //Forward declration
    class COtherClass;

    //Class declaration
    class CMyClass
    COtherClass *m_data;

    /* ---- MyClass.cpp ---- */

    #include "MyClass.h"
    #include "OtherClass.h"

    m_data = new OtherClass();

    delete m_data;



    BTW: Only cases, where you must have implementation directly in the header file, is (a) template classes and (b) inline functions. In all other cases, IMO, the implementation should never be in the header file!

Log in to reply