Inline Member Functions

Getters and setters are small, but implementing them takes an extra step. This can be very annoying.

C++ allows implementing functions where the actual definition is. This is called an "inline" implementation.

There is also another kind of "inline" implementation with the keyword "inline". Do not confuse these two. (they actually do the same thing).

Example:

class Location
{
private:
  int x,y;
public:
  int getX() { return x; }
  int getY()
  {
    return y;
  }
  void setX(int newX)
  {
    x = newX;
  }
  void setY(int newY) { y = newY; }
};

Even though inline functions are very often written in one line the formatting has absolutely nothing to do with the name. It is just a more clear way to do it, especially with one-line implementations.

When calling an inline function, instead of jumping into the function the compiler actually inserts the code wherever the function is called. This makes the code faster, but larger. For short functions this is advisable, for long functions this is a bad idea.

Why not always use inline?

  • Inline makes the executable larger.

  • One some compilers, inline code can not have conditional statements (if, case) or loops (for, while, do..while). If you use such statements in your inline functions your code will be less portable.

Guidelines for this class:

  • It is no problem if you never use inline functions

  • You should use them only for short functions that contain at most 3 statements, and no conditional / loop statements.

  • I recommoned to use them on simple getters and setters.

Practice:

Complete this class definition by providing inline getters and setters:

class Color
{
private:
  int red, green, blue;
public:
  int getRed() { return red; }
  void setRed(int r) { red = r; }
  int getGreen() { return green; }
  void setGreen(int r) { green = r; }
  int getBlue() { return blue; }
  void setBlue(int b) { blue = b; }

  void setToBlack() { red = 0; green = 0; blue = 0; }
};