Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Telescoping constructor

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

like image 476
Blackbelt Avatar asked Jul 31 '12 20:07

Blackbelt


People also ask

What is telescoping constructor?

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.

Is Builder pattern antipattern?

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.


2 Answers

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.

like image 151
yuri kilochek Avatar answered Nov 09 '22 10:11

yuri kilochek


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.

like image 24
Mark Ransom Avatar answered Nov 09 '22 11:11

Mark Ransom