May 242007
 

Invoking constructor of a constructed class!!

Read this before reading further! This is useful if you are interested in writing container classes where you need to reconstruct objects. vectors/CArrays reconstructs objects in a similar way.

#include <new .h>
class MyClass
{
   public:

      MyClass()
      {
           cout << "Previous value: " << m_nNum << endl;
           m_nNum = 20;
      }
    private:
      int m_nNum;
};

void main()
{
     // Constructor invoked once here
     MyClass mc;

     // Now we are going to invoke constructor once more
     // using placement new passing address of already created object
     // as memory location. This prevents further memory allocation and
     // the compiler calls constructor once more.
    ::new(( void* )&mc) MyClass;

     // First time printed number will be garbage, second time
     // number will be 20
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.