I have a class with two setter. One, the parameter is constant, and one is not.
class Author
{
string name;
Book* book;
public:
void setName(const string& name) { this->name = name; } // no error
void setBook(const Book* book) { this->book = book; } // error: value of const Book* cannot assign to Book*
}
My question is: why at setName method, I can make parameter constant with no error, but not in setBook.
Thanks 🙂
because you would be able to modify the object
*bookpoints to after assigning it tothis->book, thus circumventing theconstness of the argument.(you’d have to explicitly cast it to a pointer to a non-const object)
In other words,
setBook(const Book* book)means that the object pointed to bybookwill not be modified (that’s a ‘promise’ to the calling function).this->bookis however declared in a way that you can easily modify the object pointed to by it.Through the assignment
this->bookfrom the function argumentbookyou would be able to later on modify the object originally pointed to by the function argumentbook.