Is initializing const class fields using static methods good or bad practice?
I have a class that contains constant fields that need to be initialized using a function. Is it appropriate to use a static class method to initialize these values ββin the constructor's initialization list?
I still have a problem to solve, but when I read "static initialization finalization" I am worried that I am forgetting something that will come back to bite me later, and anyway I would rather get used to correct initialization.
Example:
square.hpp:
class Square
{
const double area;
static initArea(double length);
Square(double length);
}
square.cpp
Square::initArea(double length)
{
return (length * length);
}
Square::Square(double length) :
area(initArea(length))
{
return;
}
Obviously I understand that in this case you don't need a function to calculate the area, but in practice the function will define something more complex.
source to share
Is it appropriate to use a static class method to initialize these values ββin a constructor's initializer list?
Yes, this is absolutely necessary: ββstatic helper methods provide a perfect fit for this task, because they can work outside the context of any object. Therefore, it is only natural to name them inside the initializer list.
Nesting a simple function like this is probably a good idea too.
source to share