Could someone possibly post a brief explanation of the differences between member and nonmember operator overloading?

Could someone possibly post a brief explanation of the differences between member and nonmember operator overloading?

I was just thinking... if someone were to write a C++ tutorial on nothing but operator overloading and friends... that would be kick A; i would add them to my buddy list even.

There's not that much of a difference -- one is a member of a c++ class and the other isn't.

#include <iostream>
using namespace std;

class MyClass
{
public:
    void operator<<(std::string str) { cout << str;}
    std::string SayHello() {return "Hello\n";}
};

// non-member operator
ostream& operator<<(ostream& stream, class MyClass& obj)
{
    stream << obj.SayHello();
    return stream;
}

int main()
{
    MyClass obj;
    // invoke member operator
    obj << "Hello\n";
    // invoke non-member operator
    cout << obj;
    return 0;
}

I honestly don't understand overloading operators at all. Something about the left hand side and right hand side being different and whatnot... it's all a big blur right now. I read about 30 pages of my c++ text and finally just gave up, deciding to go to bed and try again tomorrow.

Maybe if you or someone else gets time, you could briefly explain how they work? I know that's a big question to ask, so if you can't no worries, i'll figure it out eventually.

see ya tomorrow.

Do you understand how function overloading works? If you do then think of operator overloading in the same way. They work because of the different parameters (if they have the same number of parameters then the parameter types must be different). The c++ compiler mangles function names by including the parameters are part of the function name, which is why you can have a c++ class with two or more functions with the same name but different parameters. Exactly how function names are mangled is compiler dependent -- compilers can do it however they wish.

I think the easiest way to get all that strait is to write a small test program, similar to what I posted above, compile for debug, then use the debugger to step through the code one line at a time so that you can see the execution flow.

This article has been dead for over six months. Start a new discussion instead.