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;
}
1
  • You could put treeItem = NULL; status = offline; into a function and call that function in both. But really, this seems fine. Commented May 5, 2012 at 3:54

3 Answers 3

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)
{
}
Sign up to request clarification or add additional context in comments.

Comments

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)
{}

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.