4

I'm learning c++ (not my choice) and faced some classes with no .cpp file. I was told that classes should be implemented in 2 files : header file (.h) and source file (.cpp) but it seems it's not always like this. My question is : When and why it is preferred to implement class methods in header file (.h) and when it's not?

Learner
  • 91
  • 8
  • Note that functions defined in headers may be inlined. This might bring higher performance with respect to some type of functions, such as `swap` (both member and non-member), move constructors, move assignment operators, destructors, etc. For instance, the execution times of sorting algorithms may differ a lot between cases where these functions may or may not be inlined. – Daniel Langr May 10 '21 at 06:47
  • Yes, performance and efficiency is a major reason why most developers choose C++ :). Anyway, this question/problem has many different aspects and you definitely cannot simply say that _"classes should be implemented in 2 files"_. Maybe, it's a good starting point, however, there are reasonable cases where one should do otherwise. (Another one is already mentioned header-only libraries, which are easy-to-use.) – Daniel Langr May 10 '21 at 07:16

1 Answers1

2

Implementations of templated classes practically have to go into headers (though see alternatives described in the link below).
Non-templated classes are indeed recommended to be split as you describe.

See Why can templates only be implemented in the header file?

Some libraries (header-only libs) consist only of headers and that is a special design decision. They have pros and cons, see https://en.wikipedia.org/wiki/Header-only
I think that is probably not what you are asking about, but the contribution (in a comment on this answer, by user super) is worth mentioning.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54