Re: class instantiation question
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.
|