Answered by:
Point of .h and .cpp

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
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).
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 -
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).
-
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.