none
Point of .h and .cpp RRS feed

  • Question

  • Hi,

    When I add a class, the IDE created two files classname.h and classname.cpp. The header file is expected to contain prototypes while the cpp file will define the detailed behavior. 

    My question is: Why I have to be bothered about this? In other words, what is the problem if I only create .h file that contains the class implementation directly without any prototypes?

    Thanks in advance

    Saturday, October 5, 2013 8:16 PM

Answers

  • If the class isn't used by other .cpp files in your program, you don't need to have a .h file separate out.   If you do use it elsewhere you need to move the declarations into the .h file which can be included elsewhere and leave the definitions in the .cpp.    The C++ language only allows things to be defined once (with the exception of inlined functions, and there's good reason why you probably don't want to inline everything in your class).

    • Proposed as answer by Jakeinc Saturday, October 5, 2013 8:51 PM
    • Marked as answer by BGQQ Sunday, October 6, 2013 12:41 PM
    Saturday, October 5, 2013 8:46 PM

All replies

  • Then any tiny change (e.g. a comment) would trigger a recompilation of every consumer of the class. If you do not want a massive compilation for every tiny change, move your implementation detail into source files and only leave contractual interface in the header.




    Visual C++ MVP

    Saturday, October 5, 2013 8:34 PM
  • If the class isn't used by other .cpp files in your program, you don't need to have a .h file separate out.   If you do use it elsewhere you need to move the declarations into the .h file which can be included elsewhere and leave the definitions in the .cpp.    The C++ language only allows things to be defined once (with the exception of inlined functions, and there's good reason why you probably don't want to inline everything in your class).

    • Proposed as answer by Jakeinc Saturday, October 5, 2013 8:51 PM
    • Marked as answer by BGQQ Sunday, October 6, 2013 12:41 PM
    Saturday, October 5, 2013 8:46 PM
  • simply add to any header

    #pragma once

    That doesn't solve the problem. If you only have one header file that contains implementation code, it is possible to have two modules that include the same header file, and this creates duplicate implementation code. The linker will complain bitterly about this.

    Therefore, implementation code belongs in a *.cpp file, not a header file.

    Sunday, October 6, 2013 12:36 AM