FAQ 14.08 When should a member function be declared as const?
The compiler won't allow a const member function to change *this or to invoke a non-const member function for this object: #include <stdexcept> using namespace std; class Stack { public: Stack() throw(); void push(int elem) throw(runtime_error); // Throws exception if numElems() is 10 int pop() throw(runtime_error); // Throws exception if numElems() is 0 int numElems() const throw(); protected: int numElems_; int data_[10]; }; int Stack::numElems() const throw() { #ifdef GENERATE_ERROR ++numElems_; //ERROR: Can't modify *this pop(); //ERROR: pop() isn't a const member function #endif return numElems_; } Although not fleshed out in this example, member functions push() and pop() may throw exceptions in certain circumstances. In this case they throw runtime_error, which is the standard exception class that is thrown for errors that are detectable only at runtime. |