2

If I have a class which will initialise a member value in such a way that it is not trivial enough to be performed directly within the initialiser list, what is the correct way of initialising that member variable?

class Rectangle
{
  private:
    const int area;

    int init_area(const int width, const int height) const { return (width*height); }

  public:
    Rectangle(const int width, const int height) : area(init_area()) {}
}

Obviously in this case initialising the Rectangle's area is trivial enough to be done inline, but let's pretend that that isn't the case and init_area() does something more complex.

Is it standard practice to initialise members this way? If so I can't seem to find it used very often in literature (the first hundred pages of cppcoreguidelines for example).

If this is not good practice please could you detail the alternative(s) and why the above method if flawed?

user7119460
  • 1,451
  • 10
  • 20
  • 5
    I'd probably make `init_area` a `static` function since it doesn't need an instance. – Fred Larson Oct 05 '17 at 18:25
  • If we assumed that init_area() relied on some other (pre-initialised) private member, would that be a valid argument for init_area() being a member function? – user7119460 Oct 05 '17 at 18:27
  • 5
    If you can assure any member it depends on is initialized before it is call, it should be ok. Remember that member variables are initialized in the order of declaration, not the order of the initializers. – Fred Larson Oct 05 '17 at 18:29
  • 2
    imho your example is a bit too simplified, in this case i would definitely call it bad practice: more code + one more method for zero gain – 463035818_is_not_an_ai Oct 05 '17 at 18:31
  • 2
    It is quite safe to use a static member function. For a complex formula this is recommended practise. As @Fred Larson said it is possible to use non-static members depending on initialisation order. As you can probably guess this is bug-bait (you can get a hard to find bug just be reordering variables in the definition). If you want to use non-static member functions then it is better to use them in the constructor body rather than the initialiser list. – Justin Finnerty Oct 05 '17 at 21:17
  • Thanks for clearing this up for me guys, appreciated! – user7119460 Oct 05 '17 at 23:01

0 Answers0