Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reuse the return value of a function multiple times in a parent constructor?

Similar to this question, but enough different that I don't think it's a duplicate:
C++ Calling a function before base-class initialization in the 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 looks ugly to me to call SettingsApp::getInstance(0) so many times when I know it's going to return the same thing every time. Can I call it once and just reuse that value in this context?
(in this case, a pointer to a SettingsApp object)

(The reason it's structured like this is because different children of Grid have different equations for pitchWidth and pitchHeight, and I want to keep the singleton idea of implicitly using the same object everywhere without actually passing it.)

like image 909
AaronD Avatar asked Jun 20 '17 07:06

AaronD


1 Answers

Create a (possibly private) ctor having as argument the value you want to compute 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))
{
}
like image 153
bolov Avatar answered Oct 23 '22 06:10

bolov