What are the advantages and disadvantages of implementing classes in header files?

后端 未结 6 1235
北荒
北荒 2020-12-03 11:49

I love the concept of DRY (don\'t repeat yourself [oops]), yet C++\'s concept of header files goes against this rule of programming. Is there any drawback to defining a clas

6条回答
  •  感动是毒
    2020-12-03 12:10

    You're not repeating yourself. You only write the code once in one header. It is repeated by the preprocessor, but that's not your problem, and it's not a violation of DRY.

    If it's right to do for templates, why not for normal classes

    It's not really that it's the right thing to do for templates. It's just the only one that really works in general.

    Anyway, if you implement a class in a header, you get the following advantages and disadvantages:

    • The full implementation is visible anywhere it is used, which makes it easy for the compiler to inline as necessary.
    • The same code will be parsed and compiled multiple times, leading to higher compile-times.
    • On the other hand, if everything is in headers, that may lead to fewer translation units, and so the compiler has to run fewer times. Ultimately, you might end up with a single translation unit, which just includes everything once, which can result in very fast compilations.

    And... that's it, really.

    Most of my code tends to be in headers, but that's because most of my code is templates.

提交回复
热议问题