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.

+3


source to share


1 answer


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.

+3


source







All Articles