Step 4 of 9
const member functions
When a member function doesn't modify the object, mark it const by writing the keyword after the parameter list:
int hp() const { return hp_; }
Why it's required, not just polite
Through a const object or a const& reference, you may only call const member functions, because only those promise not to change the object. And const& parameters are everywhere in C++ (it's the normal way to pass objects you only read). So a reading method that isn't marked const can't be used by any function that receives the object as const&.
#include <iostream>
#include <string>
class Label {
public:
explicit Label(std::string text) : text_(text) {}
std::string text() const { return text_; }
int length() const { return text_.size(); }
void shout() { text_ += "!"; }
private:
std::string text_;
};
void show(const Label& l) {
std::cout << l.text() << " (" << l.length() << ")\n";
}
int main() {
Label l("hello");
l.shout();
show(l);
}
hello! (6)
show receives a const Label&, so it can call text() and length() (both const) but not shout(). If text() weren't marked const, the call inside show wouldn't compile, with an error like 'this' argument to member function 'text' has type 'const Label', but function is not marked const. (GCC words it as passing 'const Label' as 'this' argument discards qualifiers.) Both mean: you called a non-const method on a const object.
Inside a const member function, the compiler also stops you from modifying members, so the promise is checked both ways.
Rule: mark every member function that doesn't change the object as const, from the start.
(explicit on the constructor stops a plain string from silently converting into a Label; it's good practice for single-argument constructors.)
Your turn: this doesn't compile because print_status takes a const Player& but calls methods that aren't marked const. Press Check to see the error, then fix the class (not the function).