473,772 Members | 2,414 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

conversion operator - beginner's question

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 ?
Because, in <istream>, we have operator bool() const; (in the sentry
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.

I once again state that I am not confronting the authors. I am asking
this question from learner's point of view.

Thanks
V.Subramanian
Nov 29 '07 #1
4 2023
On 2007-11-29 17:25, su************* *@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 <istream>, we have operator bool() const; (in the sentry
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
Nov 29 '07 #2
On Nov 29, 10:59 pm, "Alf P. Steinbach" <al...@start.no wrote:
* subramanian10.. .@yahoo.com, India:
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>::operato r 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
I found the following piece of code in C++ Primer 4th edition by
Stanley Lippman in page 26.

Sales_item trans;

while (std:cin >trans)
// ...

Here, isn't operator bool() called ?

Also let me know what is the correct way of doing the 'while
condition' if it is not a good way of doing.

Kindly clarify.

Thanks
V.Subramanian
Nov 30 '07 #3
su************* *@yahoo.com, India wrote:
On Nov 29, 10:59 pm, "Alf P. Steinbach" <al...@start.no wrote:
>* subramanian10.. .@yahoo.com, India:
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>::operato r 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

I found the following piece of code in C++ Primer 4th edition by
Stanley Lippman in page 26.

Sales_item trans;

while (std:cin >trans)
// ...

Here, isn't operator bool() called ?
Nope. As Alf said, the conversion involved goes to void*

Also let me know what is the correct way of doing the 'while
condition' if it is not a good way of doing.
Given the way iostreams handle things, this is a correct way to write the
while loop. However, that does not imply that it was a good idea to make
the standard streams support conversion to void*.
Best

Kai-Uwe Bux
Nov 30 '07 #4
On Nov 29, 5:25 pm, "subramanian10. ..@yahoo.com, India"
<subramanian10. ..@yahoo.comwro te:
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 ?
Pretty much so. About the only general exception I can think of
is proxies, which only work because of implcit conversions.

Otherwise, there are a few special cases; as a beginner, you
probably don't have to worry much about these, however.
Because, in <istream>, we have operator bool() const; (in the
sentry class)
This helps in
while(cin)
// ...
You're mixing up two things.

In istream and ostream, there is a nested sentry class, which
has an implicit conversion operator to bool. It is used when
writing << and >operators which go directly to the streambuf
(rather than decomposing the operation into << or >on simpler
types). The "standard" idiom here is:

std::ostream&
operator<<( std::ostream& dest, SomeType const& obj )
{
std::ostream::s entry s( dest ) ;
if ( s ) {
// do it...
}
return dest ;
}

Obviously, other alternatives (not involving the explicit
conversion) are possible, but in this (special) case, it really
doesn't matter; the class is designed to be used in one specific
case, and only in one specific case.

Both istream and ostream derive from ios, and ios has an
implicit conversion to void*. This supports idioms such as:
while ( std::cin >someVariable ) ...
or
while ( std::getline( std::cin, line ) ) ...
, the void* acting here as a bool. (The reason bool wasn't used
was because bool is an integral type, and >and << are defined
over it. So in some cases, you could get some strange overload
resolutions, rather than an error from the compiler.)

Whether this is good design or not is very debatable; as a
general rule, it is NOT a good idea to both modify program state
and have flow control in a single line/statement. Something
like:

std::cin >someVariable ;
while ( std::cin.succee ded() ) {
// ...
std::cin >someVariable ;
}

would arguably be better. Similarly, one would like to be able
to use the stream for initialization, and not just to modify
existing variables.

All one can say here is that I/O, in general, is hard, and that
iostreams works a lot better than anything else anyone has
proposed (or what's available in other languages). And the
idiom is ubiquious enough that it doesn't cause problems in
practice; everyone knows it and expects it. Since that's highly
unlikely to be the case for any class you write, you should
probably avoid such things.
So here the standard library uses a conversion operator.
The standard library does a lot of things that aren't
necessarily good practice. (The iostream's part is probably one
of the better parts of it.) But a standard library also obeys
different rules than your code, at least partially. It will be
ubiquious, and it will be well known. Which means that code
using it idiomatically will be readable, regardless of the
conventions. Your code won't have those advantages.
Are there any guidelines as to when the conversion operators
can be defined ?
Yes. Except for proxies and if you're designing the standard
library of a major language, don't. (As with all rules, there
are exceptions. But unless it is obvious that the case must be
an exception, it probably isn't.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 30 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1934
by: BigMan | last post by:
Here is a piece of code: #include <memory> using namespace std; template< typename SomeType > void f(auto_ptr_ref< SomeType >) { }
4
3221
by: Master of C++ | last post by:
Hi, This is a simple question. In the following example, .. class Vector .. { .. private: .. int *Numbers; .. int vLength; ..
5
3037
by: Vijai Kalyan | last post by:
Hello, I have come back to C++ after a couple of years with Java so I am quite rusty and this question may seem poor: My platform is Windows XP with MSVC 7.1. I have a class with a templatized conversion operator defined as follows:
16
2990
by: frs | last post by:
See example below: Why does the output of 'a' work and the output of 'b' fails to compile? Is there a way to write class 'something' so that 'b' converts correctly by default? (include iostream, string, use namespace std) template <typename T> struct something { T x; operator T();
7
3260
by: Michael Lehn | last post by:
Hi, I have a question regarding the conversion of objects. When is the conversion done by the constructor and when by the operator. My feeling tells me that the constructor is preferred. But I couldn't find the exact rule in the C++ standard. And what if the classes have template parameters? It would be great if somebody could get me a rough hint where in the
47
2878
by: rawCoder | last post by:
Hi, Just wanted to know if there is any speed difference between VB conversion Keywords like CInt, Clng, CStr, CDbl, CBool etc. ..NETs Convert.To<...> methods. And which is better to be used and why ? Thanx
1
2176
by: hunter hou | last post by:
Hello,Please look at the following code(from C++ in a nutshell) and my questions.Thanks,***Hunter... typedef void (*strproc)(const char*); void print(const char* str) { std::cout << "const char*:" << str << '\n'; } void print(int x)
10
1478
by: Jeroen | last post by:
Hi guys, Just another question. Suppose I have 2 classes (incomplete code): class A { A(const B& b); A& operator = (const A& a); }; class B {
4
2111
by: zaeminkr | last post by:
I got a good answer here I have still confusing part. I have two very simple classes class DRect { private : double x0, y0, x1, y1; public : DRect(double a, double b, double c, double d) : x0(a), y0(b),
0
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10103
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9911
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6713
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.