FAQ 14.09 Does const apply to the object s bitwise state or its abstract state?

FAQ 14.09 Does const apply to the object's bitwise state or its abstract state?

The const keyword should refer to the object's abstract state.

The const modifier is a part of the class's public: interface; therefore, it means what the designer of the public: interface wants it to mean. As an interface designer, the most useful strategy is to tie const to the object's abstract state rather than to its bitwise state. For example, in some circumstances a member function changes its object's bitwise state, yet the change doesn't cause any observable change to any of the object's public: member functions (that is, the abstract state is not changed). In this case, the member function should still be const since it never changes the meaning of the object (see FAQ 14.12). It is even more common for a member function to change an object's abstract state even though it doesn't change the object's bitwise state.

For example, the following MyString class stores its string data on the heap, pointed to by the member datum data_. (The name bad_alloc is the standard exception class that is thrown when memory is exhausted, and the name out_of_range is the standard exception class that is thrown when a parameter is out of range.)

 #include <new> #include <stdexcept> #include <iostream> using namespace std; class MyString { public:   MyString(const char* s) throw(bad_alloc);  ~MyString() throw();   MyString(const MyString& s) throw(bad_alloc);   MyString& operator= (const MyString& s) throw(bad_alloc);   unsigned size() const throw();   char& operator[] (unsigned index)       throw(out_of_range);   char  operator[] (unsigned index) const throw(out_of_range);   void toUpper() throw();  //capitalizes the string protected:   unsigned len_;   char* data_; }; int main() {   MyString s = "xyz";   for (unsigned i = 0; i < s.size(); ++i)     cout << "Character #" << i << " is " << s[i] << '\n';   s.toUpper(); } 

The abstract state of the MyString object s is represented by values returned by s[i], where i ranges from 0 to s.size() 1, inclusive. The bitwise state of a MyString is represented by the bits of s itself (that is, by s.len_ and the pointer s.data_).

Even though s.toUpper() doesn't change s.len_ or the pointer s.data_, MyString::toUpper() is a non-const member function because it changes the abstract state (the state from the user's perspective). In other words, toUpper() doesn't change the bitwise state of the object, but it does change the meaning of the object; therefore it is a non-const member function.



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