<<== <= [table of contents] [search] [glossary] [feedback] => ==>>

[online C++ tutorial]Section 7: Class Declarations

Section 7.5: Inline Functions

We've already seen how to define member functions for a class, as follows:

void Player::getTreasure() {
  health++;  // increments the value of the player's health by one
}
There's another way in C++ to define your member functions. You can define them "inline", inside the class declaration. Here's how you would define getTreasure inline:
class Player {
private:
  int health;
  int strength;
  int agility;

public:
  void move();
  void attackMonster();
  void getTreasure() { health++; } // this is the function definition
};

The braces following getTreasure() contain the entire code for the function. We don't have to define the function later in our code using the Player::getTreasure() syntax -- in fact, the compiler won't allow it, because it's already been defined here inside the class declaration.

Why inline?

As you probably noticed, it's definitely fewer keystrokes to inline a function. However, another good reason to inline is that you can sometimes speed up your program by inlining the right function. Instead of calling the function every time it is invoked, the compiler will replace the function call with a copy of the function body. If it's a small function which gets called a lot, this can sometimes speed things up.

Depending on the function, it can also be easier to read inline. If it's a function like the following:

class Math {                                // class declaration
public:
  int addTwoIntegers(int a, int b);         // function declaration
};

int Math::addTwoIntegers(int a, int b) {    // function definition
  return a + b;
}

it's probably easier to read if it's inlined:
class Math {                                // class declaration
public:
  int addTwoIntegers(int a, int b) {return a + b; } // inlined function
};                                         // (combined declaration and definition)

Why not inline everything?

Since the compiler will copy the entire function body every time the function is called, if it is a large function (more than three or four lines), inlining can increase the size of your executable program significantly. You may want to try to see what kind of speed gains you can achieve by inlining, and also compare the increase in the size of your executable.

And, just as it is sometimes easier to read functions if they are inlined, it is sometimes harder to read inlined functions. If a function is more than one or two lines, inlining it will more than likely distract a reader who is trying to understand how the class works. In these cases, it's probably better not to inline.


<<== <= [table of contents] [search] [glossary] [feedback] => ==>>