Home > C++, VC++ > Invoking constructor of a constructed class!!

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
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 }[/sourcecode]

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: