The question is as follows: Ask the following code to print a result of 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 result is not necessarily 0
The strange thing about the code is that another constructor is called in the constructor
We know that when you define an object, you do 2 things in order:
1 Allocate memory (non-static data member is uninitialized)
2 Call Constructor (constructor is intended to initialize non-static data members)
Obviously the code above, CLS obj, has allocated memory for obj, then called the default constructor, but the default constructor has not yet finished executing, but another constructor is called, which is equivalent to an anonymous temporary CLS object that calls the CLS (int) constructor. Initializes the anonymous temporary object's own data member m_i to 0, but the data members of OBJ are not initialized. So the m_i of obj is uninitialized, so the value is indeterminate.
From here, we conclude as follows:
1 in C + +, because constructors allow default parameters, the need for this constructor to call a constructor to reuse code is greatly reduced
2 If the code for another constructor is reused for just one constructor, then it is entirely possible to extract the public part of the constructor to define a member function (recommended as private) and then call the function in each constructor that requires the code.
3 occasionally we still want to invoke another constructor in the constructor of the class, which can be done in the following way:
The key to invoking another constructor in the constructor is to have the second constructor execute on the first allocated memory, rather than allocating new memory, which can be done using the placement new of the standard library:
First look at the definition of placement new in the standard library
inline void * __cdecl operator new (size_t, void * _p)
{
return (_p);
}
The new memory is not allocated.
The right way:
struct CLS
{
int m_i;
CLS (int i): m_i (i) {}
CLS ()
{
New (This) CLS (0);
}
};
Another: If the constructor calls itself, there will be infinite recursive calls that are not allowed