I'm working through the book C++ Without Fear, and I'm trying to better understand some stuff in one of the examples. Basically, I have a couple of questions that relate to the following [modified] example code from the book:

1. Lines 24-26 (marked by [Q1 relevant] in the code). If line 26 is commented out, when main runs, it will display c correctly as a series of spaces. But why should this be necessary?

In the book, Brian Overland says that you can use a line like "operator int() {return atoi(ptr);}" to convert an object's type "whenever such a conversion would supply the only way to legally evaluate an expression".

I don't understand why it makes a difference in this case. The variable c is just a series of spaces. Why should the program decide to activate the operator conversion function?

2. Line 53-4 (marked by [Q2 relevant] in the code). If I uncomment line 54, the program crashes when it's run. How come?

2. Line 53-4 (marked by [Q2 relevant] in the code). If I uncomment line 54, the program crashes when it's run. How come?

Code:

String::String(int n) {
// [Q2 relevant] If the following line is uncommented, the program crashes.
// delete [] ptr;

That's because ptr hasn't been initialized to point anywhere yet (and you should not attempt a delete on an uninitialized pointer). Since this is a constructor, a delete is pointless, but if you really wanted it there for some purpose, you could get things working with that line uncommented if you first initialized ptr to 0 (perhaps in the initializer list):

Code:

String::String(int n) : ptr(0) {
delete [] ptr;

05-20-2009

bengreenwood

Thanks.

05-20-2009

anon

Quote:

// [Q1 relevant] If the following line is commented out, c displays correctly in main.

If the following line is not commented out I get a compile error. The class itself doesn't overload operator<<, but there are two equally good conversions to choose from when you try to output it.

Conversion operators themselves are somewhat problematic. They make it harder to trace what is going on in the code - are there any implicit conversions? - and they can make unexpected and otherwise wrong code compilable. There is a reason std::string provides a method called c_str to get a constant char*, and not operator const char*.

An example of how conversion operator makes code compilable where it might not be desired. Streams provide operator void*, so they can be tested in boolean contexts, but this also makes this code acceptable: