4

I have class containing const fields which require initialisation using a function. Is it appropriate to use a static method of the class to initialise these values in the initialiser list of the constructor?

I have yet to come across a problem doing so, but as I read into the 'static initialisation fiasco' I'm concerned that I'm overlooking something which will come back to bite me later, and either way I'd rather get into the habit of initialising correctly.

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 realise in this case you don't need a function to calculate the area, but in practice the function will determine something more complicated.

3
  • 2
    You might also want to prepend that function with the type of double, remove the return from the constructor and use public: specifier where appropriate. Commented May 27, 2017 at 1:16
  • You could make initArea a free static function in the .cpp file, then it does not "pollute" the class header Commented May 27, 2017 at 1:41
  • "Static initialisation order fiasco" refers to initialisation of static-storage-duration objects (static data members and namespace-scope variables) across different files. Your case is about a non-static data member: something totally different. Commented May 27, 2017 at 4:14

1 Answer 1

4

Is it appropriate to use a static method of the class to initialize these values in the initializer list of the constructor?

Yes, this is absolutely appropriate: static helper methods provide a perfect fit for this task, because they can run outside the context of any object. Hence, it is perfectly valid to call them inside an initializer list.

Inlining a simple function like that is probably a good idea as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Great, thanks for confirming! Am I paranoid about the 'static initialisation fiasco' in this case? Or is there an edge case I should watch out for?
@user7119460 You are not initializing a static member here - static member functions are almost identical to non-member functions. As long as they are stateless (i.e. do not use static variables) there is no issue at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.