I was trying out some code of Scott Meyers Effective C++, item 3 in particular.
The code in his book should be very similar to this (he left out the constructor)
#include <iostream>
class TextBlock {
public:
TextBlock(char* ptr) : ptrText(ptr)
{}
char& operator[](std::size_t pos) const {
return ptrText[pos];
}
private :
char* ptrText;
};
int main(int argc, char* argv[]) {
const TextBlock block("Hello");
std::cout << block[0] << std::endl;
char* ptr = &block[0];
*ptr = 'J';
std::cout << block[0];
}
At the point where I change the contents in the pointer ptr (*ptr = 'J';), I get a segmentation fault (which normally happens when dereferencing an uninitialized or freed pointer). This is not happening here, what is going wrong at *ptr = 'J'
;