Inline Functions in C++

Inline Functions in C++ with Examples

A function prefixed by the keyword inline or defined within the body of the class is called inline function. Inline functions serve like compiler directive. All the inline function calls are replaced by the code of the inline functions before the code is compiled.

 It works very similar to the macros in C language. An advantage of using inline functions is that the code runs fast as the code will be available at the place where required.

So the time wasted by calling the function and returning values is saved. The drawback on the other side is that the size of the code becomes bigger as every inline function call is replaced by the body of the inline function before execution. Due to this reason the code may become inefficient and may consume a lot of resources.

 A better practice is that keep the code of inline function as short as possible. If used sensibly then it may improve the performance of the code otherwise it may behave vice versa.

Defining Inline Functions

By default all the member functions defined within the body of the class are treated as inline functions as shown in the code below.

class Person

{

public:

string name;

int age;

void speak()

{

cout<<name<<endl;

cout<<age;

}

};

In above code speak() is defined as an inline function. Although the keyword inline is not used but having said earlier, all the member functions defined within the body of a class are automatically considered as inline functions.

Alternatively, the inline functions can be declared inside the class and defined outside the body of the class as shown in the following code.

outside the body

As shown in the code above, inline function speak() is declared within the body of the class at line 11 and defined outside at line 14. If inline function is defined outside the class then it must have inline keyword before it and must have scope resolution operator (::).

We can define as many inline functions as required but should keep in mind that these functions should be as short as possible otherwise compiler may ignore them as inline and will be considered as normal functions. It is usually recommended to avoid complex logic or lengthy loops in inline functions.

Defining Inline Functions Without Class Definition

Although inline functions are defined with classes but it is important to note that inline functions are not necessarily to be used with classes. They can also be used without classes as shown in the example below.

#include “conio.h”

#include “iostream”

#include “string”

using namespace std;

inline int add(int a,int b)

{

return(a+b);

}

void main()

{

int x=11, y=22;

cout<<add(x,y);

getch();

}

More Related Articles For You

    C++ Tutorial

    C++ Quizzes