+ 1
I don't clearly understand the const functions.
Sometimes I get confused with it. So if is there any way to get a clear concept about this? Please explain me that.
1 Resposta
0
Just think of it as you promising (or instructing) the compiler not to change any of the class members (except those marked 'mutable') inside the function. In other words after running the function, the state of the class instance would not change.
for example:
class Person{
string name;
public:
void PrintName const {
cout << this->name << endl;
}
};
PrintName above is declared a constant member function, and any attempt to change the member variables of the Person class inside the PrintName function will lead to an error.
Hence, this is not allowed:
class Person{
string name;
public:
void PrintName const {
name = "New Name"; //error
cout << this->name << endl;
}
};