Junior — Middle
Is it possible to place function implementations inside header files in C++?
sobes.tech AI
Answer from AI
Yes, in C++ it is possible to place function implementations inside header files, but with some caveats:
- Functions implemented in header files should usually be declared as
inlineor be template functions to avoid multiple definition errors during linking. - This is often used for template functions and classes, as their implementation needs to be available in all translation units.
Example:
// header.h
inline int add(int a, int b) {
return a + b;
}
If a function is not declared as inline and implemented in a header file, including this file in multiple cpp files will cause a multiple definition error.
Therefore, implementing functions in header files is a common practice for templates and inline functions, but for regular functions, it is preferable to place the implementation in cpp files.