I am reading a book called 'Effective C++, Second Edition' and its talking about const member functions and how you have bitwise const-ness and conceptual const-ness.
It says most compilers will go with bitwise const-ness, which is that you cannot alter data members of an object inside a const member function.
Then there's an example of a member function that doesn't seem to act bitwise in the const test.
It goes like this:
#include "stdafx.h"
#include <string>
#include <iostream.h>
using namespace std;
class mystring
{
public:
mystring(const char* value);
operator char *() const { return data; }
private:
char * data;
};
mystring::mystring(const char * value)
{
mystring::data = const_cast<char*>(value);
}
int main(int argc, char* argv[])
{
const mystring s = "Hello";
char * nasty = s;
*nasty = 'M';
printf("s: %c", s);
return 0;
}
When this is run, it says in my book it should allow you to change the value of s, even though its const. This because char* data is pointing to the same as const char* value is pointing. *data in this case is not const.
However trying to run this in MS VC++ 6.0, it throws an access violation at line *nasty = 'M';
Can someone explain what is going on? I think I've missed something?
To me it seems that because we have a const mystring s
, we should not be able to change it, but then what it says in the books seems awkward.