FAQ 22.10 What if one member object has to be initialized using another member object?

Comment the declaration of the affected data members with the comment //ORDER DEPENDENCY.

If a constructor initializes a member object of the this object using another member object of the this object, rearranging the data members in the class body could break the constructor (see FAQ 22.08). This important maintenance constraint should be documented in the class body. For example, in the constructor that follows, the initializer for data_ uses len_ to avoid a redundant call to strlen(s), thus introducing an order dependency in the class body.

 #include <new> using namespace std; class MyString { public:   MyString(const char* s)               throw(bad_alloc);                                         // Promote const char*   MyString(const MyString& s)           throw(bad_alloc);                                         // Copy constructor   MyString& operator= (const MyString&) throw(bad_alloc);                                         // Assignment  ~MyString()                            throw(); protected:   unsigned len_;    // ORDER DEPENDENCY   char*    data_;   // ORDER DEPENDENCY }; MyString::MyString(const char* s) throw(bad_alloc) : len_ ( strlen(s)        ) , data_( new char[len_+1] ) { memcpy(data_, s, len_+1); } MyString::~MyString() throw() { delete[] data_; } int main() { MyString s = "xyzzy"; } 

Note that the //ORDER DEPENDENCY comment is attached to the affected data members in the class body, not to the constructor initialization list. This is because the order of member objects in the class body is critical; the order of initializers in the constructor initialization list is irrelevant (see FAQ 22.07).



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