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
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.
When Builder Is an Antipattern. Unfortunately, many developers pick only part of the Builder pattern — the ability to set fields individually. The second part — presence of reasonable defaults for remaining fields — is often ignored. As a consequence, it's quite easy to get incomplete (partially initialized) POJO.
This is called delegating constructor in c++11 and is done like so:
MyClass::MyClass(QWidget *parent)
: MyClass(NULL, NULL, NULL, parent)
{
}
whereas your version produces a temporary that gets immediately destroyed.
The easiest way is to supply default values to the constructor parameters.
If that doesn't work, you typically create an Init
method that gets called by each constructor so that the code isn't repeated.
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