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.)
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))
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With