Answer: In the following scenarios we should use inline function in c++ programming.
When to Use Inline function in C++:
1) When the member functions are very small e.g. only returning value or having very small statements then we should use inline member function in C++ class. As they are not taking much space and avoid cost of function call.
class A{
public:
Void objsAlive(){
Return objCount;
}
private:
int objCount;
}
2) If the small member functions (little bit larger than above example or same) have frequent call. e.g.
class A{
public:
double GetCounter()
{
LARGE_INTEGER li;
if( 0 == m_counterStart )
{
return 0;
}
else
{
QueryPerformanceCounter( &li );
return double( li.QuadPart - m_counterStart ) / m_counterFreq;
}
}
}
3) Code readability: very small functions are understandable itself and no need to put any comment about the function. At the same point declaration and definition we can understand what function is about e.g.
class A{
public:
void Counter() { objCount++; } // By default inlined function.
// no need to put comment about GetCriticalSection()function.
LPCRITICAL_SECTION GetCriticalSection()//By default inlined
{
return &m_cs_queue;
}
}
4) In some of the scenarios we have to make use of inline function in c++ program instead of MACRO as we may get undesired result with MACRO.
In below example, we are using MACRO and inline function doing the same job i.e. double the number passed.
We’ll be using the value of variable int a=2; and pass parameter as (++a) to both MACRO and inline function.
So, value of passing parameter will be 3 on increment and expected result from both MACRO and inline function would be square i.e. 9.
But with MACRO, we will be getting undesired result i.e.16 instead of 9 as MACRO, SQUARE (++X) expands to ++x * ++x, which will increment the value of x twice i.e. 4 and give the result equals 4*4 =16.
This problem will not occur in inline member function in C++ program.
#define SQUARE(X) X*X //MACRO to double the number.
class A{
public:
int Square(int a);////inline function to double the number .
};
inline int A::Square(int a)
{
return a*a;
}
int main()
{
//Using MACRO
int a=2;
int c = SQUARE(++a);
printf("Result using MACRO: %d\n",c);//Expected result is 9 but getting 16.
//Using inline function
A obj;
a=2;
int d = obj.Square(++a);
printf("Result using C++ inline function: %d\n",d); // Expected result i.e. 9
return 0;
}
Output:
Result using MACRO: 16
Result using C++ inline function: 9