Operator overloading in C++

I did my first operator overloading in C++ today. My code ended up being quite different to the example code that I found, but I think I’m happy with it:

class FileData {
public:
  FileData( const string& path );
  static bool LessThan( const FileData& a, const FileData& b );
  bool operator< ( const FileData& );
  unsigned long size() const { return m_size; }
private:
  unsigned long m_size;
  char m_md5[ 16 ];
};

static bool operator< ( const FileData& a, const FileData& b ) {
  return FileData::LessThan( a, b );
}

bool FileData::operator< ( const FileData& b ) {
  return FileData::LessThan( *this, b );
}

bool FileData::LessThan ( const FileData& a, const FileData& b ) {
  unsigned long a_size = a.size();
  unsigned long b_size = b.size();
  if ( a_size == b_size ) {
    return memcmp( a.m_md5, b.m_md5, 16 ) < 0;
  }
  return a_size < b_size;
}

I'm not sure when it becomes either useful or necessary to define the operator both as a static and as a member function. I did both because I wasn't sure what was required.

Leave a Reply