On 2007-11-29 17:25, subramanian100in@yahoo.com, India wrote:
> In the book, C++ Coding Standards book by Hereb Sutter and Andrei
> Alexandrescu, in Item 40 on pages 86-87 viz, "Avoid providing implicit
> conversions", the authors have advised the use of named functions that
> offer conversions instead of conversion operators.
>
> In page 87, example 2: Errors that work.
>
> class String
> {
> // ...
> public:
> operator cons char *(); // deplorable form
> };
>
> Assume s1, s2 are 'String's:
> int x = s1 -s2; // compiles; undefined behaviour
> const char *p = s1 - 5; // compiles; undefined behaviour
> ...
>
> I am NOT going against the authors in asking the following.
> However, as a beginner I just to want to know if conversion operators
> should be avoided totally ?
You should never say never, there are no absolute rules. Though in most
cases it is advisable to follow them, especially if you are a beginner.
But if you know what you are doing then there situations where they can
be useful.
> Because, in
> class)
>
> This helps in
> while(cin)
> // ...
>
> So here the standard library uses a conversion operator. Are there any
> guidelines as to when the conversion operators can be defined ?
>
> Kindly clarify.
One example where they might be useful is when creating proxy-objects,
then it might have a conversion to the object-type it is acting as a
proxy for.
--
Erik Wikström