Hi,
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?
Thanks for your help.Code:#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; class String { private: char *ptr; public: String(); String(int n); String(const char *s); String(const String &src); ~String(); String& operator=(const String &src) {cpy(src.ptr); return *this;} String& operator=(const char *s) { cpy(s); return *this;} int operator==(const String &other); operator char*() {return ptr;} // [Q1 relevant] If the following line is commented out, c displays correctly in main. operator int() {return atoi(ptr);} void cpy(const char *s); }; int main() { String a("3"); cout << a << endl; String c(3); cout << "This is c: [" << c << "]"; return 0; } // ------------------------ // STRING CLASS FUNCTIONS String::String() { ptr = new char[1]; ptr[0] = '\0'; } String::String(int n) { // [Q2 relevant] If the following line is uncommented, the program crashes. // delete [] ptr; int i; ptr = new char[n + 1]; for (i = 0; i < n; i++) ptr[i] = ' '; ptr[i] = '\0'; } String::String(const char *s) { int n = strlen(s); ptr = new char[n + 1]; strcpy(ptr, s); } String::String(const String &src) { int n = strlen(src.ptr); ptr = new char[n + 1]; strcpy(ptr, src.ptr); } String::~String() { delete [] ptr; } int String:: operator==(const String &other) { return (strcmp(ptr, other.ptr) == 0); } // cpy -- Copy string function // void String::cpy(const char *s) { delete [] ptr; int n = strlen(s); ptr = new char[n + 1]; strcpy(ptr, s); }