I have the following code which I wrote to test the const member function: It compiles and runs fine when I have the const qualifier for the data member char *data and to the argument for the constructor. However if I remove const from the data member and the constructor, i get compiler error. Is it because the string "Hello World" is always of type const char * ?
#include <iostream>
#include <string.h>
using namespace std;
class mystring {
const char *data;
mutable int length;
mutable int valid;
public:
mystring(const char *str) {data = str;}
~mystring() { };
int GetLength() const;
};
int mystring::GetLength() const
{
if (valid)
return length;
else {
length = strlen(data);
valid = 1;
return length;
}
}
int main()
{
const char *str = "Hello World";
mystring s(str);
cout << s.GetLength() << endl;
}
strinmain? - James McNellismystring s = "Hello World"will compile perfectly fine with your code even if you removeconstas you describe in your question. Also, when you have problems with "compiler errors", you have to post the exact errors you are getting. Nobody here is telepathic. - AnT