In Java, it is often visible that the constructor of the class calls another constructor. However, in C ++, this requirement is greatly reduced because the constructor allows default parameters. In this case, we may occasionally want to call another constructor in the class constructor. We know that when constructing an object, we will do two things: 1. allocate memory 2 and execute the constructor; so the key to calling another constructor In the constructor is to let the second constructor execute on the memory allocated for the first time, instead of allocating new memory, this can be done using placement new in the Standard Library:
Let's take a look at the definition of placement new in the standard library.
Inline void * _ cdecl operator new (size_t, void * _ p)
{Return (_ p );}
No new memory is allocated.
# Include
Class My
{
Public:
My ()
{
New (this) My (5 );
}
My (int I)
{
A = I;
}
Int;
};
Note that if a member variable is initialized in the first constructor and another constructor is called, the same member variable is initialized in the constructor, this will cause the same member variable to be initialized twice. But this problem also exists in Java, so pay attention to the sequence during programming.