<<< Functors     Index     Do not overload logical operators! >>>

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!

<<< Functors     Index     Do not overload logical operators! >>>