Consider the following code:
class A
{
B* b; // an A object owns a B object
A() : b(NULL) { } // we don\'t know what b will be when constructing A
Like the others have already suggested: Try placement new..
Here is a complete example:
#include
#include
class B
{
public:
int dummy;
B (int arg)
{
dummy = arg;
printf ("C'Tor called\n");
}
~B ()
{
printf ("D'tor called\n");
}
};
void called_often (B * arg)
{
// call D'tor without freeing memory:
arg->~B();
// call C'tor without allocating memory:
arg = new(arg) B(10);
}
int main (int argc, char **args)
{
B test(1);
called_often (&test);
}