Hi,

I need to finish a assignment on operator overloading but this one piece of code doesnt seem to make sense..

in my int main() i have

int main()
{

Element a, b(5), c(7), d;
cout << (5+b) << endl;

this is just part of it, I have already implemented the overloading functions
but from my understanding the overloading operators of class works eg:

a + b would be a.operator+(b) but then how can 5+b be 5.operator+(b) since 5 is a int.
Please can same one help?

Thanks

>>a + b would be a.operator+(b) but then how can 5+b be 5.operator+(b) since 5 is a int.

You're wrong. Although you can make an overloaded operator as a member function (i.e. a.operator+(b)), that's not the preferred way, normally it is implemented as a free-function. As so:

// this will cover the ( a + b ) case:
Element operator + (const Element& a, const Element& b);

// this will cover the ( 5 + b ) case:
Element operator + (int a, const Element& b);

// this will cover the ( a + 5 ) case:
Element operator + (const Element& a, int b);

Overloaded operators should almost always be implemented as (friend) free-functions, not as member functions. The only exception to that rule is for the operators that cannot be implemented as free-functions, like assignment operators and a few others.

Thank you very much! That was very helpful. Now I can continue my assignment with confidence!

My compiler keeps saying that 'Element Element::operator+(int, const Element&) can only take one or no parameters

I think the problem is that you've declared it as a member function. Make sure the function is written as Mike said, e.g.

Element operator + (int a, const Element& b)  // note: not "Element::operator +"
{
    Element return_val;
    // make return_val be the sum of a and b
    return return_val;
}

and declare the function to be a friend of your class:

class Element {
    public:
        ...
        friend Element operator + (int a, Element & b);
        ...
};

Do the same for all three versions of your operator+.

I did that too... gcc compiler still says that the function can only take one or no argument

It works now, the problem was that I kept implementing it with Element:: making the friend functions part of the class Element which was obviously incorrect. I blindly missed the point raptr_dflo and mike where stating. 100% solved.
Thanks guys

This question has already been answered. Start a new discussion instead.