Print
Category: C++ Programming
Hits: 2604

Inline methods are very useful for to tune your code for performance. Placing the keyword inline before a method tells the compiler to copy the code instead of calling the method over the stack. The effect is similar like a macro, but doesn't need any preprocessor. Anyway this is not a must to the compiler. He will decide himself if he wants and is able to call a method as inline.

There is also a disadvantage using inline: The binary code is getting bigger and has lots of redundancy. Therefore using inline makes sence for small methods, like delegating or simply getting or setting values to a class, without any checks.

Note that inline can be used only in header files!!

Inline methods might be used also for virtual methods. Some programmers see no sence doing this. But because this is just a succestion for the compiler he will even call the virtual method inline if he can. Normaly he won't because of the polymorphism.

Following example shows the use of inline methods:


class TTest : public TZObject
{
  public:
    ...
    inline Int getValue() const 
    { return m_iValue; }
    
    inline void setValue(Int iValue) 
    { m_iValue = iValue; }
  
    Int getInverseValue() const;  
  private:
    Int m_iValue;
};

//Inline can be used even outside of the 
// class declaration But it must stay in 
// the header file
inline Int TTest::getInverseValue() const
{
  return -m_iValue;
}