This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Implicit conversion error using g++


Daniel.Walker@lhsl.com wrote:

> I have a question about when g++ accepts implicit conversions using user
> defined types and when it doesn't. Consider:
>
> class Foo  { };
>
> class Bar {
>     public: operator Foo() { return Foo(); }
> };
>
> class Baz {
>     public: Baz(const Foo & f) { }
> };
>
> int main(int argc, char ** argv) {
>     Bar bar;
>     Baz b1(bar);     // line 13
>     Baz b2 = bar;   // line 14, error
> }
>
> I get the following error with gcc v3 (prerelease) 20010514:
> g++ foo.cpp
> foo.cpp: In function `int main(int, char**)':
> foo.cpp:14: conversion from `Bar' to non-scalar type `Baz' requested
>
> Why are lines 13 and 14 not equivalent? Initializing b1 uses Bar's cast
> operator implicitly but initializing b2 doesn't. Could someone please
> explain what g++'s policy is and also what does ISO say about user defined
> casts during initialization? I appreciate it!

Ok, please correct me if I am wrong.
1. Line 13 and 14 are not "equivalent" (whatever this word may mean)
because they translate into different function calls:
Line 13 would be replaced by these calls:
- bar.Foo()
- Baz(const Foo&)
Line 14 would be replaced by:
- Baz()
- Baz.operator=(const Bar)
I think that the missing operator= is the reason why the automatic casting
doesn't work in your code.

--
David Berthelot



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]