Re: class instantiation question
On Jul 1, 5:16 am, "hill....@gmail.com" <hill....@gmail.com> wrote:
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 assig=
nment" <<
endl; return *this; };
operator int() { cout << "call operator int()" <<endl; re=
turn 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".
Because that's what is required by the standard. Because the
source type is the same as the target type, the copy
initialization basically becomes the same as direct
initialization, e.g. as if you'd written
ctest cc( ctest() ) ;
The only constructor which can be called is the one taking an
int, so the compiler converts your expression into an int, using
the user defined conversion operator, and calls it.
Maybe you meant for the copy constructor (and the assignment
operator, while we're at it, although it isn't used in your
example) to take references to const, as is the normal case.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34