Skip to content

Instantly share code, notes, and snippets.

@icholy
Created December 10, 2012 18:15
Show Gist options
  • Save icholy/4252248 to your computer and use it in GitHub Desktop.
Save icholy/4252248 to your computer and use it in GitHub Desktop.
inline functions

Even though overuse of getter and setter functions can be frowned upon, they can help a lot if you're looking to provide a intuitive api. However the overhead the additional function call introduces in undesirable. Thankfully, there's the inline keyword. It tells the compiler to replace each invokation of the function with the body of the function.

struct Foo {
  int m_number = 123;

  inline int number () {
    return m_number;
  }
};

int main () {
  Foo foo;

  // used like a regular function
  std::cout << foo.number() << std::endl;

  // treated like
  std::cout << foo.m_number << std::endl;

  return 0; 
}

However the inline keyword isn't a guarantee that the compiler will do this. A function delcared inline could not be optimized and vice versa. So it's more of a hint to the compiler.

Another important piece of information is that the function definition needs to be available in every translation unit.

foo.h

inline int foo ();

foo.cpp

#include "foo.h"

int foo () {
  return 123;
}

If I try to use the foo function by including foo.h I'd get a warning telling me that the foo is not defined. This won't prevent compilation, but the function will not get inlined. The compiler needs access to the function body to replace it with the call site. There's a simple solution though. Just put the function definition in the header.

foo.h

inline int foo () {
  return 123;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment