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:
getWidth()
that computes the width
and cleans up the constructor? Something like width(getWidth(_chart_width))
.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.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.