Search code examples
c++operator-overloadingfriend

friend in operator == or << when should i use it?


I feel I have a bit of a hole in my understanding of the friend keyword.

I have a class, presentation. I use it in my code for two variables, present1 and present2, which I compare with ==:

if(present1==present2)

Here's how I defined the operator == (in class presentation):

bool operator==(const presentation& p) const;

However, I was told that using friend and defining it outside of the class is better:

friend bool operator==(presentation&, presentation&);

Why? What's the difference between the two?


Solution

  • In the first case, your function operator== is a nonstatic class member. It has therefore access to private and protected member variables.

    In the second case, the operator is externally declared, therefore it should be defined as a friend of the class to access those member variables.