Why can a pointer still modify const reference object inside function?

Viewed 73

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?

0 Answers
Related