Class constructor is automatically called when an object instance is generated. Generally, constructor cannot be called directly.
However, in some special usage, developers need to call constructors to generate object instances.
For example, in memory pool programming, you need to apply for a large common memory in advance and convert a small block into an object instance during use,
In this scenario, you need to explicitly call the constructor.
Define Class AA:
Class AA {public: AA () {printf ("Hello AA: AA ();/N"); temp = 10 ;}; virtual ~ AA () {}; int Geti () {return temp ;}; PRIVATE: int temp ;};
We apply for a piece of memory in advance:
Char * PTR = (char *) malloc (sizeof (AA ));
When necessary, we need to convert the PTR to an AA object instance. If you use the following method to call it:
AA * AA = (AA *) PTR;
The constructor of Class AA will not be aroused, so this memory is not an AA object instance.
In this case, perform the following operations: AA-> Geti ();
No error is reported in the vc6.0 environment, but the returned data is incorrect.
Then we cannot use the memory as an AA instance. In this case, we need to use an explicit constructor call:
AA * AA = new (PTR) AA ();
Then, the constructor of AA is invoked to construct the instance.