Is it possible to reuse the return value of a function several times in the parent constructor?

Similar to this question, but different enough that I don't think this is a duplicate:
C ++ function call before initializing base class in initialization list


I have this constructor:

EditorGrid::EditorGrid(int width, int height) : Grid(width , //workingWidth height , //workingHeight (SettingsApp::getInstance(0)->iconSize + SettingsApp::getInstance(0)->iconSpace ) , //pitchWidth (SettingsApp::getInstance(0)->iconSize + SettingsApp::getInstance(0)->iconSpace + SettingsApp::getInstance(0)->iconLabel) //pitchHeight ) { //EditorGrid-specific setup } 

It works, but it seems ugly to call SettingsApp::getInstance(0) so many times when I know that it will return the same every time. Can I call it once and just reuse this value in this context?
(in this case, a pointer to the SettingsApp object)

(The reason it is structured is because different Grid children have different equations for pitchWidth and pitchHeight , and I want the singleton idea to implicitly use the same object everywhere, without passing it at all.)

+5
source share
1 answer

Create a (possibly private) ctor that takes as an argument a value that you want to calculate only once and delegate to it:

 EditorGrid::EditorGrid(int width, int height, /*your_type*/& instance_0) : Grid(width, height, instance_0.iconSize + instance_0.iconSpace, instance_0.iconSize + instance_0.iconSpace + instance_0.iconLabel { //EditorGrid-specific setup } EditorGrid::EditorGrid(int width, int height) : EditorGrid(width, height, *SettingsApp::getInstance(0)) { } 
+6
source

Source: https://habr.com/ru/post/1269012/


All Articles