views:

362

answers:

3

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?

+1  A: 

You answered your own question, they are indeed inline methods.

Reasons to use them are performance.

Gamecat
Still, this doesn't mean that the compiler will inline them, only that you don't manually have to add the *hint* that the "inline" keyword really is.
Johann Gerell
+8  A: 

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.

Adam Rosenfield
Yes, but "inline by default" doesn't mean that the compiler will inline them, only that you don't manually have to add the *hint* that the "inline" keyword really is.
Johann Gerell
+6  A: 

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.

Gerald
No need to clutter source file with trivial code.
Martin York