Search code examples
c++const-cast

Can one override my const C++ member function returning a const pointer to a internal non-const array using const_cast?


I'm learning c++ and came 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 a user can do

Test t("hi");
const_cast<char*>(t.getName())[0] = 'z'; //modifies private data...

Is this fine ? I mean modifying private data since the purpose of return const char* was to prevent changing private data. How do I prevent this ? (without using std::string)


Solution

  • No this is not 'fine'. Though it is possible. But C++ doesn't force good behavior on programmers. It mainly allows you to declare things in a way that show their intended use. If a programmer decides to trick around that protection he should know what he is doing.

    Bjarne Stroustrup: Yes. That's the new cast syntax. Casts do provide an essential service. The new syntax is an improvement over the C-style casts because it allows the compiler to check for errors that it couldn't with the old syntax. But the new syntax was made deliberately ugly, because casting is still an ugly and often unsafe operation.