0

I have a question about a custom forward iterator in cpp.

I'm not understanding why I need to declare the overload function == and != friend instead in the other overload operation functions like pre-increment and dereference we can avoid the use of the keyword friend.

It is just because in the equals and not equals function am I comparing two different iterators and I need to access the private members of these objects?

class _iterator {
    private:
        ...

    public:
        using iterator_category = std::forward_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = T;
        using pointer = value_type*;
        using reference = value_type&;

        _iterator(...) : ... { }

        reference operator* () const { 
            ...
        }

        _iterator& operator++ () { 
            ... 
        }

        _iterator& operator++ (int) {
            ...
        }

        friend bool operator== (const _iterator& a, const _iterator& b) { 
            ...
        }

        friend bool operator!= (const _iterator& a, const _iterator& b) { 
            ...
        }   
};
carlo97
  • 69
  • 6
  • 1
    Because you're defining the overloaded `operator==` and `operator!=` as **non-member functions** in your case while `operator++` and `operator*` as **member functions**. – Anoop Rana Feb 17 '22 at 13:43
  • Ok. But I can not write them as member functions. Because I will retrieve this error: `overloaded 'operator==' must be a binary operator (has 3 parameters)` – carlo97 Feb 17 '22 at 13:57
  • 1
    But in your posted code snippet, you have aready defined `operator*` and `operator++` as member functions so you do not `friend` keyword for them. – Anoop Rana Feb 17 '22 at 14:00
  • 1
    related/dupe: https://stackoverflow.com/questions/9476974/why-should-we-use-a-friend-function-to-define-the-comparison-operator – NathanOliver Feb 17 '22 at 14:03
  • @AnoopRana But why I can not write the `oeprator==` as member functions? – carlo97 Feb 17 '22 at 14:08
  • @carlo97 It is possible to overload `operator==` as member function as well. Then you won't need the `friend` keyword anymore. See [DEMO](https://onlinegdb.com/vg3yNlLnj) – Anoop Rana Feb 17 '22 at 14:19
  • Ok but as I told previously if I declare the `operator==` as member function I am getting this error: `overloaded 'operator==' must be a binary operator (has 3 parameters)` – carlo97 Feb 17 '22 at 14:23
  • @carlo97 Note in my demo, the overloaded `operator==` only takes 1 **explicit** parameter. So to solve your error, you've to remove the first explicit parameter named `a` too. For example, the modified definition will look like: `bool operator== (const _iterator& b) { }`. Note i have removed the first explicit parameter named `a` but still there is an implicit `this` parameter. – Anoop Rana Feb 17 '22 at 14:27

0 Answers0