I frequently run into large, non-template classes in C++ where simple methods are defined directly in the class body in the header file instead of separately in the implementation file. For example:
class Foo {
int getBar() const { return bar; }
...
};
Why do this? It seems like there are disadvantages. The implementation is not as hidden as it should be, the code is less readable, and there would also be an increased burden on the compiler if the class's header file is included in many different places.
My guess is that people intend for these functions to be inlined in other modules, which could improve performance significantly. However, I've heard newer compilers can do inlining (and other interprocedural optimizations) at link-time across modules. How broad is the support for this kind of link-time optimization, and does it actually make these kind of definitions unnecessary? Are there any other good reasons for these definitions?
The C++ standard says that methods defined inside the class definition are inline
by default. This results in obvious performance gains for simplistic functions such as getters and setters. Link-time cross-module optimization is harder, although some compilers can do it.
Often there's no reason other than it's just easier and saves time. It also saves a little clutter in the implementation file, while taking up the same number of lines in the header file. And being less readable is quite a stretch if it's limited to things like getters and setters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With