Search code examples
c++syntaxconstructorcode-formattinginitialization-list

C++ Initialization list with expressions


I've just learned that I should be using an initialization list instead of assignments in my C++ constructors. Here is my example.

**Assignment Example: **

Class Graph {
private:
    int count;
    int spacing;
    int width;

public:
    Graph(int _count, int _spacing, int _chart_width) {
        count = _count;
        spacing = _spacing;
        width = (_chart_width - ((_count - 1) * _spacing)) / _count;
    }
};

**Initialization List Example: **

Class Graph {
private:
    int count;
    int spacing;
    int width;

public:
    Graph(int _count, int _spacing, int _chart_width) : count(_count), spacing(_spacing), width((_chart_width - ((_count - 1) * _spacing)) / _count) {}
};

As you can see, this looks really ugly.

My question is:

  1. Is this the way to write an Initialization list constructor with expressions?
  2. Is there a better syntax? What if the expression is really long and makes the Initialization list syntax completely unreadable?
  3. Should I write a method getWidth() that computes the width and cleans up the constructor? Something like width(getWidth(_chart_width)).
  4. Initialization list syntax indicates that, for example, count(_count) is a function that takes in _count as an input argument. Am I mixing up the Initialization list syntax with function syntax? or is count() truly a function? This is very confusing.
  5. If the way I am writing the Initialization list is correct, can you please suggest a better way to format the code for readability? I guess, I would like to know what is the most common syntax for long Initialization lists.

Solution

  • Different projects (and people) have different coding standards and tastes, but personally I find this formatting very readable:

    Class Graph {
      private:
        int count;
        int spacing;
        int width;
    
      public:
        Graph(int _count, int _spacing, int _chart_width)
            : count(_count), spacing(_spacing),
              width((_chart_width - ((_count - 1) * _spacing)) / _count)
        {}
    };
    

    And no, these are not necessarily function calls. But they can be... The best way to think about it is the following: if the variables you are initializing are instances of a class, then you are calling the constructor to initialize them. If you view it this way, the syntax makes sense.

    And I would recommend a helper function (as a private and maybe static method of the class) for calculating the width.