Calling a constructor to re-initialize object

is it possible to re-initialize an object of a class using its constructor?


Sort of. Given a class A:

A a;
...
a = A();   

the last statement is not initialisation, it is assignment, but it probably does what you want.


Literally? Yes, by using placement new. But first you have to destruct the previously constructed object.

SomeClass object(1, 2, 3);
...
object.~SomeClass(); // destruct
new(&object) SomeClass(4, 5, 6); // reconstruct
...
// Final destruction will be done implicitly

The value of this does not go beyond purely theoretical though. Don't do it in practice. The whole thing is ugly beyond description.


It's possible, although it's a very bad idea. The reason why is that without calling the destructors on the existing object, you are going to leak resources.

With that major caveat, if you insist on doing it, you can use placement new.

// Construct the class
CLASS cl(args);

// And reconstruct it...
new (&cl) CLASS(args);

In C++11, you can do this:

#include <type_traits>

template <class T, typename... Args>
void Reconstruct(T& x, Args&&... args)
{
    static_assert(!std::has_virtual_destructor<T>::value, "Unsafe"); 
    x.~T();
    new (&x) T(std::forward<Args>(args)...);
}

This allows you to use Reconstruct passing arbitrary constructor parameters to any object. This can avoid having to maintain a bunch of Clear methods, and bugs that can easily go unnoticed if at some point the object changes, and the Clear method no longer matches the constructor.

The above will work fine in most contexts, but fail horribly if the reference is to a base within a derived object that has a virtual destructor. For this reason, the above implementation prevents use with objects that have a virtual destructor.