2

Assume I have Student class like this:

class Student {
  private:
    std::string _name;
  public:
    Student(const std::string&);
    void setName(const std::string&);
    const std::string& getName() const;
};

And a function which is like:

void changeConstRefObj(const Student& student){
   std::string newName = ....;
   student.setName(newName);
}

Which is invalid when you call setName. But you can still use a pointer to call setName (which does not use static_cast, may be something wrong with compiler?) like this:

void changeConstRefObj(const Student& student)
{
    std::string newName = ...;
    Student *p = (Student*)(&student);
    p->setName(newName);
}

Or using new object like this one below (which I don't know why it works).

void changeConstRefObj(const Student& student)
{
    std::string newName = ...;
    Student t(newName);
    Student *p = (Student*)(&student);
    *p = t;
}

I thought that if I use const that I wouldn't be able to change the object but through a pointer I can change it easily. Why is that the case?

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
  • `I thought that if I use const that I can not change object` correct. `but through pointer I can change it easily.` because you casted away the constness. – tkausl Mar 21 '21 at 02:56
  • 1
    This is why C-style casts (at least for pointers and references) are unsafe... – HTNW Mar 21 '21 at 02:56
  • The `const` keyword is there to help you avoid making mistakes; that doesn't mean you can't defeat it (by casting-away-const using `const_cast(&student)`, or C-style casting as in your example) and make those mistakes anyway, if you really want to. As the saying goes, `const` is meant to protect you from Murphy, not Machiavelli. – Jeremy Friesner Mar 21 '21 at 03:00
  • 2
    It's worth mentioning that even if this runs, it's undefined behavior. C++ is allowed to assume that variables declared `const` will not change, so the compiler can optimize around that fact freely – Silvio Mayolo Mar 21 '21 at 03:38
  • *"which does not use `static_cast`"* -- misleading at best (and I think you meant `const_cast` here, as a `static_cast` cannot remove `const`). Your code uses a [C-style cast](https://en.cppreference.com/w/c/language/cast), which can do everything `const_cast` can do, plus more. – JaMiT Mar 21 '21 at 03:40
  • Found a related question instead of a true duplicate: [I'm changing the value of a const variable by accessing the memory location. Why doesn't it work?](https://stackoverflow.com/questions/27258089/im-changing-the-value-of-a-const-variable-by-accessing-the-memory-location-why) I guess that other question would be the next step from this one, as it assumes your syntax works. – JaMiT Mar 21 '21 at 04:03

0 Answers0