From Effective Java 2ed Item 2:
telescoping constructor pattern, in which you provide a constructor
with only the required parameters, another with a single optional
parameter, a third with two optional parameters, and so on,
culminating in a constructor with all the optional parameter
Can I do the same in C++? I tried somthing like this:
MyClass::MyClass(QWidget *parent)
{
MyClass(NULL, NULL, NULL, parent);
}
MyClass::MyClass(QString title, QWidget *parent)
{
MyClass(title, NULL, NULL, parent);
}
MyClass::MyClass(QString title, QString rightButton, QWidget *parent)
{
MyClass(title, NULL, rightButton, parent);
}
MyClass::MyClass(QString titleLabel, QString leftButtonLabel, QString rightButtonLabel, QWidget *parent)
: QWidget(parent)
{
// construct the object
}
but it does not work. Any hint?
I am really new in C++ field so.. sorry for the newbee question
The easiest way is to supply default values to the constructor parameters.
If that doesn’t work, you typically create an
Initmethod that gets called by each constructor so that the code isn’t repeated.