On 1 jul, 00:24, Elias Salom?o Helou Neto <eshn...@gmail.com>
wrote:
On 1 jul, 00:16, "hill....@gmail.com" <hill....@gmail.com>
wrote:
Hi,
I stuck into this problem that I can't figure it out.
Here is the class definition:
class ctest {
public:
ctest(void) { cout << "ctest default constor"
<< endl; }; ctest(ctest& c) { cout <<"ctest
copy constr" << endl; }; ctest(int a) { cout
<<"ctest int constor" <<endl; };
ctest& operator= (ctest& a) { cout << "ctest
copy assignment" <<
endl; return *this; };
operator int() { cout << "call operator int()"
<<endl; return 20; }
};
int main(void)
{
ctest cc = ctest();
}
And it outputs as following:
ctest default constor
call operator int()
ctest int constor
I wonder why it will invoke "operator int()" and call
"constructor with int as argument".
Thanks
Brad
I wonder where is the
return( 0 );
statement.
Well, it does not quite solve the problem. In fact, the issue
here is const-correctness, because ctest() must be used as
const, but ctest has ctest& or int as arguments, being the
second the only possible the compiler tryes to find a
conversion. The following does not compile:
#include <iostream>
class ctest {
public:
ctest(void) { std::cout << "ctest default
constor" << std::endl; };
ctest(ctest& c) { std::cout <<"ctest copy
constr" << std::endl; };
//ctest(int a) { std::cout <<"ctest int constor"
<< std::endl; };
ctest& operator= (ctest& a) { std::cout <<
"ctest copy assignment" << std::endl; return *this; };
//operator int() { std::cout << "call operator
int()" << std::endl; return 20; }
};
int main(void)
{
ctest cc = ctest();
return( 0 );
}
but the following does:
#include <iostream>
class ctest {
public:
ctest(void) { std::cout << "ctest default
constor" << std::endl; };
ctest(const ctest& c) { std::cout <<"ctest copy
constr" << std::endl; };
ctest(int a) { std::cout <<"ctest int constor" <<
std::endl; };
ctest& operator= (ctest& a) { std::cout <<
"ctest copy assignment" << std::endl; return *this; };
operator int() { std::cout << "call operator
int()" << std::endl; return 20; }
};
int main(void)
{
ctest cc = ctest();
return( 0 );
}
and prints
ctest default constor
only once, because of optimization, I guess.
14.00.50727.42 without any optimization option.
I comment out ctest(int a) and operator int() it still compiles.
ctest() has two part. First part is that ctest() will create a
temp ctest object using default constructor. And second part is
as argument. Because that temp ctest is a const, and my original