A question about constructor function
class T
{
public:
int m_i ;
T () { m_i = 1 ; }
T(int k ) { T() ; }
};
int main()
{
T t(0 );
cout<< t.m_i <<endl;
return 0;
}
When i invoke a constructor funciton within another constructor funciton , this constructor will not impact on this object .
In the above sample code , The t.m_i will remain uninitialize . why
? i test it in VC6.
I have gone throught the ISO C++ specificaiton , but no any thread was been found .
Re: A question about constructor function
Quote:
Originally posted by flysnow
When i invoke a constructor funciton within another constructor funciton , this constructor will not impact on this object .
In the above sample code , The t.m_i will remain uninitialize . why
? i test it in VC6.
The reason is quite simple...the call to the first constructor inside your second one will create a temporar instance of 'T' which is only valid for the current scope thus only until the second constructor returns...
You can easily see what happens while debugging through the construction of the instance of 'T'...take a look at the 'this' pointers...the following code demonstrates the problem as well...just run it and look at the output...
Code:
#include <iostream>
#include <iomanip>
class T
{
public:
int m_i ;
T()
{
std::cout << "First constructor = 0x" << std::hex << this << std::endl;
m_i = 1 ;
}
T(int k)
{
std::cout << "Second constructor = 0x" << std::hex << this << std::endl;
T();
}
~T()
{
std::cout << "Destructor = 0x" << std::hex << this << std::endl;
}
};
int main()
{
{
T t(0);
std::cout << "Instance created" << std::endl;
}
return 0;
}
Are there some c++ expert here ?
I know the result , but why? why was the temporary object created ?
Is it a normal behavior defined by C++ specificaiton ?
Thanks Mikey and Andreas Masur .
The code is just for describing the problem . so i put the m_i public. :)