Topic: Implicit casts


Author: djones@megatest.com (Dave Jones)
Date: Fri, 19 Feb 1993 02:15:57 GMT
Raw View
A cohort here at my own place of business answered my question, which was...

> Gotcha number one is found on page 232 of Stroustrup's bible, 2nd edition:
> "There can be no implicit conversion from a user-defined type to a basic
> type (because the basic types are not classes);" So defining an implicit
> conversion from Char_String to const char* is right out. Why? Seems like
> all that would be needed is a syntax for it.

It doesn't mean what it says. Implicit conversions are indeed possible, just
not by means of constructors.

My question is answered just below the quoted text on page 232.
Perhaps I should have read on. There is indeed a syntax for defining
a type-conversion operator. I thought I remembered that from the previous time
I studied C++, before a six month LOA, but I let the statement above make
me believe that I must have remembered wrong.

Anyway, the syntax is like this:

class Char_String {
 private:
  char *str;
 public:
  operator const char* () { return str; }
}

The problem of using the operator only for implicit casts of member-function
arguments remains. There is no way I know of to constrain the use other than
saying, "Kids, don't use this operator at home. It's for implicit conversion of
arguments of member-functions of class Char_String only. If you don't know
what that means, don't worry about it."

Is there a way to enforce that rule? Either there should be, or there is
a better way to do what I'm doing. (See previous post with this "Subject"
line.) It wouldn't surprise me at all to learn that there is a better way,
but I can't think of one.

I'm going to be away for a couple or three weeks, so if you respond to
this, or if you have already responded to the original, would you please
email me a copy?

 djones@megatest.com

By the time I return, the response will probably be past its use-by date
and dumped in the bit bucket.

Thanks,

 Dave




Author: bs@alice.att.com (Bjarne Stroustrup)
Date: 21 Feb 93 21:35:37 GMT
Raw View

djones@megatest.com (Dave Jones @ Megatest Corporation) writes

 > Gotcha number one is found on page 232 of Stroustrup's bible, 2nd edition:
 > "There can be no implicit conversion from a user-defined type to a basic
 > type (because the basic types are not classes);" So defining an implicit
 > conversion from Char_String to const char* is right out. Why? Seems like
 > all that would be needed is a syntax for it. But Okay, I can live with that,
 > if I must.

The sentense you quote is preceeded by ``Using a constructor to specify
type conversion'' and followed by an explanantion, complete with example,
of how to specify an implicit conversion from a class to a built-in type.
Foe example:

 class tiny {
  // ...
 public:
  operator int(); // convert from tiny to int
  // ...
 };

 void f(tiny t)
 {
  int i = t; // meaning t.operator int()
 }