Why should I not include cpp files and instead use a header?

后端 未结 13 2295
天涯浪人
天涯浪人 2020-11-22 07:13

So I finished my first C++ programming assignment and received my grade. But according to the grading, I lost marks for including cpp files instead of compiling and li

13条回答
  •  囚心锁ツ
    2020-11-22 07:31

    re-usability, architecture and data encapsulation

    here's an example:

    say you create a cpp file which contains a simple form of string routines all in a class mystring, you place the class decl for this in a mystring.h compiling mystring.cpp to a .obj file

    now in your main program (e.g. main.cpp) you include header and link with the mystring.obj. to use mystring in your program you don't care about the details how mystring is implemented since the header says what it can do

    now if a buddy wants to use your mystring class you give him mystring.h and the mystring.obj, he also doesn't necessarily need to know how it works as long as it works.

    later if you have more such .obj files you can combine them into a .lib file and link to that instead.

    you can also decide to change the mystring.cpp file and implement it more effectively, this will not affect your main.cpp or your buddies program.

提交回复
热议问题