I am learning C ++ and have come across this const_cast operator. Consider the following example:
class Test
{
private:
char name[100];
public:
Test(const char* n) { std::strncpy(name, n, 99); name[99]=0; }
const char* getName() const { return name; }
}
Now the user can execute
Test t("hi");
const_cast<char*>(t.getName())[0] = 'z';
It's fine? I mean changing private data, since the purpose of return const char * was to prevent changing private data. How can I prevent this? (without using std :: string)
source
share