The following is a question: Is the printing result of the following code 0?
# Include <stdlib. h>
# Include <iostream>
Using namespace STD;
Struct CLS
{
Int m_ I;
CLS (int I): m_ I (I ){}
CLS ()
{
CLS (0 );
}
};
Int main ()
{
Cls obj;
Cout <obj. m_ I <Endl;
System ("pause ");
Return 0;
}
The printed results are not necessarily set to 0.
The strange thing about the code is that the constructor calls another constructor of its own.
We know that when defining an object, we will do two things in order:
1) allocated memory (non-static data members are not initialized)
2) Call the constructor (the intention of the constructor is to initialize non-static data members)
Apparently, in the code above, cls obj; the memory has been allocated to OBJ, and then the default constructor is called. However, the default constructor has not been executed yet, but another constructor is called, this is equivalent to generating an anonymous temporary CLS object. It calls the CLS (INT) constructor and initializes m_ I, the data member of the anonymous temporary object, to 0; however, the data member of obj is not initialized. Therefore, m_ I of obj is not initialized, so its value is also uncertain.
Here, we will summarize the following:
1) In C ++, the constructor allows default parameters, which greatly reduces the need for calling constructor to reuse code.
2) If you only reuse the code of another constructor for one constructor, you can extract the public part of the constructor and define a member function (private is recommended ), then you can call this function in every constructor that requires this code.
3) occasionally we want to call another constructor In the constructor of the class, which can be done as follows:
The key to calling another constructor In the constructor is to execute the second constructor on the memory allocated for the first time, instead of allocating new memory. This can be done using the placement new of 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.
The correct method:
Struct CLS
{
Int m_ I;
CLS (int I): m_ I (I ){}
CLS ()
{
New (this) CLS (0 );
}
};
In addition, if the constructor calls itself, there will be infinite recursive calls, which are not allowed.
From http://www.cnblogs.com/chio/archive/2007/10/20/931043.html