How to properly call one constructor from another

This issue was found in LibreOffice project. The error is detected by the following diagnostic: V603 The object was created but it is not being used. If you wish to call constructor, ‘this->Guess::Guess(….)’ should be used.

Guess::Guess()
{
  language_str = DEFAULT_LANGUAGE;
  country_str = DEFAULT_COUNTRY;
  encoding_str = DEFAULT_ENCODING;
}

Guess::Guess(const char * guess_str)
{
  Guess();
  ....
}

Explanation

Good programmers hate writing duplicate code. And that’s great. But when dealing with constructors, many shoot themselves in the foot, trying to make their code short and neat.

You see, a constructor can’t simply be called like an ordinary function. If we write “A::A(int x) { A(); }”, it will lead to creating a temporary unnamed object of the A type, instead of calling a constructor without arguments.

This is exactly what happens in the code sample above: a temporary unnamed object Guess() is created and gets immediately destroyed, while the class member language_str and others remain uninitialized.

Correct code:

There used to be 3 ways to avoid duplicate code in constructors. Let’s see what they were.

16dc94

The first way is to implement a separate initialization function, and call it from both constructors. We’ll spare you the examples – it should be obvious as it is.

That’s a fine, reliable, clear, and safe technique. However, some bad programmers want to make their code even shorter. So we have to mention two other methods.

They are pretty dangerous, and require you to have a good understanding of how they work, and what consequences you may have to face.

The second way:

Guess::Guess(const char * guess_str)
{
  new (this) Guess();
  ....
}

Third way:

Guess::Guess(const char * guess_str)
{
  this->Guess();
  ....
}

The second and the third variant are rather dangerous because the base classes are initialized twice. Such code can cause subtle bugs, and do more harm than good. Consider an example where such a constructor call is appropriate, where it’s not.

Here is a case where everything is fine:

class SomeClass
{
  int x, y;
public:
  SomeClass() { new (this) SomeClass(0,0); }
  SomeClass(int xx, int yy) : x(xx), y(yy) {}
};

The code is safe and works well since the class only contains simple data types, and is not derived from other classes. A double constructor call won’t pose any danger.

And here’s another example where explicitly calling a constructor will cause an error:

class Base 
{ 
public: 
 char *ptr; 
 std::vector vect; 
 Base() { ptr = new char[1000]; } 
 ~Base() { delete [] ptr; } 
}; 
 
class Derived : Base 
{ 
  Derived(Foo foo) { } 
  Derived(Bar bar) { 
     new (this) Derived(bar.foo); 
  }
  Derived(Bar bar, int) { 
     this->Derived(bar.foo); 
  }
}

So we call the constructor using the expressions “new (this) Derived(bar.foo);” or “this->Derived(bar.foo)”.

The Base object is already created, and the fields are initialized. Calling the constructor once again will cause double initialization. As a result, a pointer to the newly allocated memory chunk will be written into ptr, which will result in a memory leak. As for double initialization of an object of the std::vector type, the consequences of it are even harder to predict. One thing is clear: code like that is not permissible.

Do you need all that headache, after all? If you can’t utilize C++11’s features, then use method No. 1 (create an initialization function). An explicit constructor call may be only needed on very rare occasions.

Recommendation

And now we have a feature to help us with the constructors, at last!

C++11 allows constructors to call other peer constructors (known as delegation). This allows constructors to utilize another constructor’s behavior with a minimum of added code.

For example:

Guess::Guess(const char * guess_str) : Guess()
{
  ....
}

To learn more about delegating constructors, see the following links:

  1. Wikipedia. C++11. Object construction improvement.
  2. C++11 FAQ. Delegating constructors.
  3. MSDN. Uniform Initialization and Delegating Constructors.

Written by Andrey Karpov.

This error was found with PVS-Studio static analysis tool.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s