An inline function is a function in which body is inserted in the place of its call. These functions can be compared with Macros. Inline functions are used to improve performance of the application. However, many inline functions can lead your program to grow up in size. That is why often only small functions are declared as inline.
There are two ways to make your functions to be inline. The first one consists in simple definition of member function in the body of class declaration:
class Person { public: //an inline function string getFirstName() { return firstName; } private: string firstName; string lastName; tm dateOfBirth; };
getFirstName is an inline function in this case.
Another possibility is to use inline keyword with definition of function. In this case, you have to declare function in the same way as you declare a simple function:
//declaration of an inline function string getLastName()
The definition of an inline function must be done in the same header file with class declaration. It is very important to follow this rule; because you can get Linker error in the case, you define inline function in a .cpp file. The definition of the inline function must use the inline keyword:
//getLastName is in the same header file with declaration of //Person class inline string Person::getLastName() { return lastName; }
The use of inline functions has following advantages:
- The removing of some unnecessary instructions for function’s call make programs faster.
- When many small functions are often called compiler generates more code for function’s calls. The correct use of inline functions makes programs smaller.
Sometimes it seems that inline functions can increase performance of an application. However, the use of many inline functions can cause different problems:
- Many inline functions can cause the growth of binary executable file.
- Inline function must be declared in every compilation unit where it is used.