Inlining Members


Well structured C++ classes often contain many small methods. If each such method required the overhead of a function call, the performance of such classes would be negatively impacted. Fortunately, C++ supplies the facility of inlining functions.

The inline type specifier may be applied to the declaration of a method. The method's definition may then follow the class declaration.

Defining a method within a class is equivalent to declaring it as being inline and providing the definition of the method immediately following the class declaration.

Consider the following example.

int i=0;
 
class test
{
 public:
  int i;
 
  inline int value();
};
 
int test::value() {return i;}

Note that the 'i' referred to by the definition of the method test::value is the member i (within the class). The code shown above is equivalent to the following:

class test
{
 public:
  int i;
 
  int value() {return i;}
};

where the method test::value is 'automatically inlined'. A C++ compiler converts the first example (where the inline was explicitly specified and the definition followed the class) to the second (where the method was defined within the class). This conversion is done after preprocessing but prior to parameter type checking and analysis of the syntax of the method; thus, inlined methods possess a special property that allows them to be defined even within nested or local classes where it would be syntactically invalid for them to be defined if they were not inlined.