A member function with the const keyword after its parameter list cannot modify its object's fields:
class Counter {
public:
int get() const { return count; }
void reset() const { count = 0; } // ERROR.
private:
int count;
};A const object can only call its const methods:
class Counter {
public:
Counter() : count(0) {}
int get() const { return count; }
void increment() { count++; }
private:
int count;
};
const Counter c;
c.get(); // OK.
c.increment(); // ERROR.This also applies when an object is passed by const reference:
void print(const Counter& c) {
std::cout << c.get() << "\n"; // OK.
c.increment(); // ERROR.
}When a const method is defined outside the class, const must appear on both the declaration and the definition:
class Counter {
public:
int get() const;
private:
int count;
};
int Counter::get() const {
return count;
}
Dan