Inline functions

When is a function not a function?

Short functions which are called frequently are often declared as inline. Accessors and mutators are prime examples of functions which are candidates to be inline.

When the compiler sees a function call to an inline function, it replaces the function call with the code in the body of the function. The original code looks like a function call, but no function call is actually made at runtime.

How do I create an inline function?

To declare a function inline, precede the function declaration and function defintion with the keyword inline. Any member function whose code is written in the class definition is automatically considered inline.

Because the compiler needs to have access to the body of the inline function, the inline function must be written or #included in the header file.

class Bob { public: Bob ( void ); // an implicit inline function int GetSize( void ) const { return m_size; } // explicitly inline below void SetSize( int size ) ; private: int m_size; }; // explict inline SetSize inline void Bob::SetSize( int size ) { m_size = size; } // inline non-member function inline void PrintBob ( const Bob& bob ) { cout << bob.GetSize( ) << endl; } Notice that the constructor and other member functions which are not inline would be defined in the .cpp file.

To make the code a bit easier to read, we prefer to define the functions outide the class definition (like SetSize()) rather than in the class definition (like GetSize( )). Also note that declaring a function inline is just a recommendation to the compiler which it may choose to ignore.

All of this sounds great. Is there a downside? Of course.

Last Modified: Monday, 28-Aug-2006 10:16:07 EDT