Tuesday, August 7, 2007

Calling class Constructor C++

Some times we may think it would be nice , if we can call the constructor again for some initialization stuff (Normally constructor does the initialization job).  It is not possible to call the constructor of a class explicitly. Only way is to call is new operator. So here is that.

It is achived using placement new technique. it is very easy. For example if you have class CAlgoritham and the constructor of CAlgoritham does most of the initialization works. So after some processing you may want to  reset it to the old state (may be depnds on the algoritham). You have already wrote the initialization codes in constructor , but it is not possible to call constructor again. So we can use placement new. Here it is


CAlgoritham alg; //member variables Initialized already
alg.DoProces113();


new (&alg)CAlgoritham(); //this will call consructor again.But it  will not create a new memory (since we are giving memory location).


The statement new (&alg)CAlgoritham() is equal to CAlgoritham::CAlgoritham();

I like this kinda of things. Hopes you too. 

No comments: