FAQ 14.08 When should a member function be declared as const ?

FAQ 14.08 When should a member function be declared as const?

graphics/new_icon.gif

There are two ways to look at it. When looking at the member function from the inside out, the answer is "whenever the member function wants to guarantee that it won't make any observable changes to its this object." When looking at the member function from the outside in, the answer is "whenever a caller needs to invoke the member function via a reference-to-const or pointer-to-const." Hopefully these two approaches end up agreeing with each other. If not, then the application may have a serious design flaw, or perhaps it needs to be const overloaded (that is, two member functions with the same name and the same parameters, but one is a const member function and the other is not).

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net