Skip to main content

18.3) Other Refinements


Methods that are small and contain minimal logic can be inlined into (i.e., implemented wholly within) the class definition. The code for an inlined method will be inserted into your program wherever calls have been made to that method – essentially removing the need for a method call and improving performance a little, at the cost of duplicated code.

Another refinement is to use initializer list syntax in constructors, to copy values into instance variables. An initializer list is a comma-separated list of instance variable names, each of which is followed by brackets and the desired value for the instance variable. Normally, this value comes from a constructor parameter. Initializer list syntax allows the compiler to generate more efficient object initialization code but it is not appropriate in all situations. For example, it can't be used if we need to do any validation of constructor parameters.

Applying both refinements to the Rectangle class, we get this:

class Rectangle
{
  public:
    Rectangle(int x, int y, int w, int h):
      corner_x(x), corner_y(y), width(w), height(h) {}
    int get_x() const { return corner_x; }
    int get_y() const { return corner_y; }
    int get_width() const { return width; }
    int get_height() const { return height; }
  private:
    int corner_x;
    int corner_y;
    int width;
    int height;
};