We will introduce in detail the basic application methods of C ++ constructor today. It is hoped that beginners can fully grasp this knowledge through the content introduced in this article, so as to gain help in practical application in the future, and to a certain extent deepen their understanding of this language.
- Detailed description of C ++ bit operations
- How to use C ++ Endian
- How to use C ++ switch-case statements
- How To Connect C ++ to MySqL database
- Analysis of basic application methods of C ++ youyuan Functions
We know that when defining an object, we will do two things in order:
1) The allocated non-static data members are not initialized)
2) The purpose of calling the C ++ 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 need to call constructor to reuse code is greatly reduced because constructor allows default parameters.
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 C ++ 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 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.
The correct method:
- struct CLS
- {
- int m_i;
- CLS( int i ) : m_i(i){}
- CLS()
- {
- new (this)CLS(0);
- }
- };
In addition, if the C ++ constructor calls itself, there will be infinite recursive calls, which are not allowed.