Hendrik Schober
11/6/2008 1:37:00 PM
coolguyaroundyou@gmail.com wrote:
> Consider the following codes:
>
> class abc
> {
> int i;
>
> public:
> abc() : i(0) {}
> void func() { .....some code....}
> };
>
> void func2(const abc& Obj)
> {
> .....some code...
> }
>
>
> int main()
> {
> func2(12);...................//CALL 1
>
> const abc obj;
> obj.func();..................// CALL 2
>
> abc().func();...............// CALL 3
>
> return 0;
> }
>
> CALL 1 takes place fine by implicit conversion of 5 to an abc object.
> But, if the func2() paramater is kept non-const, then it gives
> error !! WHY??
In the code you supplied CALL 1 won't compile. Please make
sure you provide code we can paste and compile to observe
what you claim to see. (That's an FAQ. Please take the time
to read and understand the relevant portions of the FAQ
before you ask here.)
Assuming you have 'abc::abc(int)' forgotten to paste, but
have it in your real code: A ctor taking one argument (or
taking more, but the other's are optional) which isn't
marked as 'explicit' is an user-defined implicit conversion
operator. If, where an 'abc' is needed, you supply something
else, and if it takes only one user-defined conversion, the
compiler will employ such ctors to perform the conversion.
Thus, 'func2(12)' is converted to 'func1(abc(12))' and this
is fine, since the compiler can bind temporaries to const
references. If, however, 'func2()' takes a non-const reference
it won't compile, because it isn't allowed to bind temporaries
to non-const references.
> CALL2 doesn't take place because we are calling a non-const function
> on a const object. That's understood.
>
> If you say that the reason for CALL 1 not taking place in case of non-
> const function parameter is that the temporary object created is a
> const, then what is the reason for CALL 3 taking place successfully??
The temporary isn't 'const'. It's an rvalue. You can call member
functions, even non-const ones, on rvalues of user-defined types
(even though you cannot modify rvalues of built-in types).
> I'm really confused regarding this problem.
>
>
> Are temporary objects const??
> If not, then why do we need the prototype of func2 as reference to a
> const?
HTH,
Schobi