Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are C++ methods sometimes defined inside classes?

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?

like image 981
Jay Conrod Avatar asked Nov 05 '08 21:11

Jay Conrod


Video Answer


2 Answers

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.

like image 77
Adam Rosenfield Avatar answered Sep 27 '22 22:09

Adam Rosenfield


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.

like image 26
Gerald Avatar answered Sep 27 '22 22:09

Gerald