Question

I came across a header file that includes various function prototype declarations which are inline and const:

inline bool Foo1() const;
inline bool Foo2() const;
inline bool Foo3() const;
...

I understand that the inline keyword allows for the compiler to (potentially) expand the function when it is called, but why not include the body of the function?

It'd make more sense to me if the definition was included in the header file:

inline bool Foo1() const { return m_Foo1; };
inline bool Foo2() const { return m_Foo2; };
inline bool Foo3() const { return m_Foo3; };
...

What is the point of using inline on the prototype?

Was it helpful?

Solution

It's possible that it was just a mistake, but most likely the programmer wanted to make the function inline but didn't want to clutter that portion of the file with the implementations of these functions. This is a fairly common pattern when writing "header only" code. You have a normal header file with no (or few) implementations and another file that is included but acts like an implementation file and contains all the implementations.

OTHER TIPS

It's simply allowing a class interface to be displayed compactly.

The function definitions exist later in the compilation unit (before they are called, if they are called)

From Dr. Dobb's:

Either a function definition or a function prototype may be declared inline. If a function prototype is declared inline, a separate definition of the function must appear somewhere else in the module if the function is called

There are a number of reasons.

  1. You need the empty function declaration to resolve dependency issues where one function calls another.
  2. For stylistic reasons.

The only constraint is that the function definition must be included in every compilation unit that uses the inline function. Otherwise inline functions are exactly the same as ordinary functions in how they are declared and defined.

Because the functions are probably in the object files and the developer doesn't want anyone to see the source code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top