Re: conversion operator - beginner's question
* subramanian100in@yahoo.com, India:
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 ?
No, just avoid them as default, and think /very/ carefully before
providing one.
Because, in <istream>, we have operator bool() const; (in the sentry
class)
The sentry class is just a specification "implementation" detail, a
helper abstraction used to specify the functionality. You will never
use that operator bool() directly. Additionally, the modern templated
standard iostreams are not an example of good design. They're an
example of lack of design and/or bad design. Simply put, if some way of
doing things is employed by standard iostreams, then you know that it's
most probably something to not adopt in your own designs, that it's most
probably something to stay very very clear of, to fear and avoid.
This helps in
while(cin)
// ...
No, what's invoked here is "std::basic_ios<char>::operator void*".
That's still an example of an Evil(TM) way of doing things.
With billions of good ways to do this, it might seem fantastic and
unbelievable that one of the very few really Evil ways ended up in the
standard, sort of like "we really need some more Evil, let's see...",
but such is standardization, and ask me not why: it's a mystery.
So here the standard library uses a conversion operator. Are there any
guidelines as to when the conversion operators can be defined ?
A conversion operator can implement a logical IsA relationship where
inheritance isn't applicable.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?