CIS-255 Home http://www.c-jump.com/bcc/c255c/c255syllabus.htm

Operator Overloading


  1. C++ Operators
  2. Kinds of operators
  3. Arguments of operators
  4. Rational numbers
  5. Rational number examples
  6. Rational number approximation
  7. Binary member operator syntax
  8. Unary member operator syntax
  9. Non-member binary operator syntax
  10. Available operators
  11. Special operators
  12. lvalue explained
  13. Assignment operators
  14. operator= and copy constructor
  15. Common uses of operators
  16. Increment ++ and decrement -- syntax
  17. The dual operator[] idiom
  18. Conversion by constructor
  19. Conversion by constructor mix-up
  20. Functors
  21. Caution: when operator overloading can hurt your users
  22. Do not overload logical operators!
  23. Advice

1. C++ Operators



2. Kinds of operators



3. Arguments of operators



4. Rational numbers



5. Rational number examples



6. Rational number approximation



7. Binary member operator syntax



8. Unary member operator syntax



9. Non-member binary operator syntax



10. Available operators



11. Special operators



12. lvalue explained



13. Assignment operators



14. operator= and copy constructor



15. Common uses of operators



16. Increment ++ and decrement -- syntax



17. The dual operator[] idiom



18. Conversion by constructor



19. Conversion by constructor mix-up



20. Functors



21. Caution: when operator overloading can hurt your users

  • Consider:

    
    #include <iostream>
    
    class BoolFlag { 
        bool m_flag;
    public:
        BoolFlag( bool flag )
        : m_flag( flag )
        {
        }
    
        bool operator|| ( BoolFlag const& other )
        {
            return m_flag || other.m_flag;
        }
    };
    
    BoolFlag download( char const* URL )
    {
        std::cout << "Dowloading " << URL << '\n';
        //...
        return BoolFlag( true );
    }
    
    
  • 
    int main( )
    {
        char const* URL = "www.xyz.com/lib/file.xml";
        BoolFlag download_complete = download( URL );
    
        if ( download_complete || download( URL ) ) {
            // process file...
        }
        return 0;
    }
    
    
  • Do not overload operators

    
        || and &&
    
    
  • Clients will expect usual semantics...

    ...and you can't provide them!

22. Do not overload logical operators!



23. Advice