0

Consider the following instructor , I had to initialize treeItem and status anyway , but in a overloaded function , I can introduce the id variable as well.

But it looks silly , I shouldn't be doing this in both of the functions , any suggestions ?

Contact ()
{
    treeItem = NULL;
    status = offline;
}

Contact (const QString & id)
{
    treeItem = NULL;
    status = offline;

    this->id = id;
}
daisy
  • 22,498
  • 29
  • 129
  • 265
  • You could put treeItem = NULL; status = offline; into a function and call that function in both. But really, this seems fine. – Justin May 05 '12 at 03:54

3 Answers3

2

You'd benefit from a ctor-initializer-list, but until you upgrade to C++11, you do need to duplicate variable initialization for each constructor.

One option would be to use default arguments to reduce the number of constructors, as in:

Contact (const QString& identifier = QString())
    : treeItem(NULL), status(offline), id(identifier)
{
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1

Use a default argument to avoid explicitly defining two constructors. And use initializer lists. Like so:

Contact (const QString & id = QString())
    : treeItem(NULL)
    , status(offline)
    , id(id) // yes this works but you may wish to change the parameter name)
{}

Or in C++11 with delegating constructors::

Contact ()
    : treeItem(NULL)
    , status(offline)
{}

Contact (const QString & id = QString())
    : Contact()
    , id(id)
{}
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

If you truly want to overload the constructor (as opposed to supplying default values), the best you can do is move the common code into its own function, then call it from each of the constructors:

Contact()
{
    init();
}

Contact(const QString &id)
{
    init();
    this->id = id;
}

private void init() {
    treeItem = NULL;
    status = offline;
}
Adam Liss
  • 47,594
  • 12
  • 108
  • 150