I am going through operator overloading in C++ and have a question.
What if both friend and member operator overloaded functions are present? Which will be called?
A minimal example for the + operator is below.
#include <iostream> class myTime { private: int mm,hh; public: myTime(): mm(0), hh(0) {} myTime(int mm1, int hh1) :mm(mm1), hh(hh1) {} myTime( const myTime & ref) : mm(ref.mm), hh(ref.hh) {} friend myTime operator +(myTime &t1, myTime &t2); myTime operator+ (const myTime &ref); void display() { std:: cout << " Hrs = " << hh << " mins = " << mm << std::endl;} }; myTime operator + (myTime &t1, myTime &t2) { int mm2, hh2; std::cout << "Friend Operator" << std::endl; mm2 = (t1.mm + t2.mm) %60; hh2 = (t1.mm + t2.mm)/60 + (t1.hh + t2.hh); return (myTime(mm2,hh2)); } myTime myTime::operator+ (const myTime &ref) { int mm2, hh2; std::cout << " Member operator" << std::endl; mm2 = (ref.mm + mm)%60; hh2 = (ref.mm + mm)/60 + (ref.hh + hh); return (myTime(mm2,hh2)); } int main() { myTime t1(30,3); myTime t2(50,4); myTime t3; t3 = t1+t2; t3.display(); } When run on my machine (gcc 4.8.3 Windows), the friend function is called. Will this be the same on all machines?
Edit With the + operator changed to const the member operator is executed.
public: myTime(): mm(0), hh(0) {} myTime(int mm1, int hh1) :mm(mm1), hh(hh1) {} myTime( const myTime & ref) : mm(ref.mm), hh(ref.hh) {} friend myTime operator +(const myTime &t1, const myTime &t2); myTime operator+ (const myTime &ref); void display() { std:: cout << " Hrs = " << hh << " mins = " << mm << std::endl;} }; again why?
friendisn't really the issue here; that's an implementation detail. The question is about a non-member function versus a member function.