FAQ 24.01 What should assignment operators return?

Assignment operators should generally return *this by reference. This means that they adhere to the same convention used by the built-in types by allowing assignment to be used as an expression rather than simply as a statement. This allows assignment to be cascaded into larger expressions. An example follows.

 #include <iostream> using namespace std; class Fred { public:   Fred(int i=3) throw();   Fred& operator= (const Fred& x) throw();   friend int operator== (const Fred& a, const Fred& b) throw(); protected:   int i_; }; Fred::Fred(int i) throw() : i_(i) { } Fred& Fred::operator= (const Fred& x) throw() { i_ = x.i_; return *this; } int operator== (const Fred& a, const Fred& b) throw() { return a.i_ == b.i_; } int main() {   Fred x, y, z;   x = y = 5;                                         <-- 1   if ((z = x) == y)                                  <-- 2     cout << "z (which was assigned from x) is equal to y\n"; } 

(1) Result of y = 5 used as an expression

(2) Result of z = x used as an expression



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