Is it possible to override the const member function of C ++ by returning a const pointer to an internal non-constant array using const_cast?

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'; //modifies private data...

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)

+5
source share
2 answers

, "". . ++ . , . , , .

Bjarne Stroustrup: . . . C- , , . , - .

+6

, , const_cast. , const, , . , - , const_cast , const.

+4

All Articles