On 19 May 2004 07:00:32 -0700,
(velthuijsen) wrote:
>I've created a class
>MyClass
>{
>public:
> MyClass();
> MyClass(int);
> MyClass& operator=(const MyClass& Right);
> ...
>private:
> ...
>}
>
>In my code I used to test it out I have
>
>MyClass Test;
>...
>int i = 5;
>...
>Test = i;
>...
>
>The Test = i results in a temporary MyClass being constructed using
>the MyClass(int) constructor.
>How can I prevent that from happening?
C++ will take the "path of least resistance", to a certain extent, in order
to find a way to make things compile. Since you didn't provide an
assignment operator that accepts an int directly, it figures out that it
can get from what you've written to something that works with the
assignment operator you /did/ provide: It applies the user-defined
conversion of int-to-MyClass via MyClass(int). If you simply provide an
additional assignment operator that takes int directly, it will use that
right off the bat, and you'll be saved the extra constructor. See the code
in my reply to Sharad in this thread.
-leor
--
Leor Zolman --- BD Software ---
www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html