0

I am trying to perform following operation,

ABC a1;
ABC a2=2+a1;

I have tried using overloading using friend function

ABC operator+(double h, ABC a){
   return a+h;            //consider this + to be overloaded
}

But it does not work. I don't know of any other way to do this, Please help!

Krishanu
  • 552
  • 3
  • 21
  • 2
    What do you mean by "it does not work"? Can you follow stackoverflow.com's instructions for creating a [mre] when answering that? – Sam Varshavchik Oct 21 '20 at 13:26
  • Please provide [mcve] preferably using https://godbolt.org/ – Marek R Oct 21 '20 at 13:26
  • 2
    The code you've shown could be made to work, so whatever the problem was it is somewhere in the code you didn't show. As usual saying 'it does not work' is no help whatsoever. More details please. – john Oct 21 '20 at 13:30

1 Answers1

0
class A {
public:
    A(double x) : v{x} {}

    A add(const A& b) const
    {
        return v + b.v;
    }

private:
    double v;
};

A operator+(const A& a, const A& b)
{
    return a.add(b);
}

int main()
{
    A a{3};
    auto x = 5 + a;
    auto y = a + 7;
    
    return 0;
}

https://godbolt.org/z/1TxWYE

Note overloads for operator+ are not needed since implicit conversion provided by constructor solves the issue.

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • Just OOC, why bother with the member function? If you want a `operator+=` (which `operator+` can be implemented in terms of, and usually should) then sure, [it should be a member](https://stackoverflow.com/a/4421719/364696), but if only `operator+` should exist (for whatever weird reason the OP might have), is there a strong reason to prefer a public member function `add` over just making `operator+` a `friend`? Seems odd to expand the public interface unnecessarily. – ShadowRanger Oct 21 '20 at 13:39
  • I'll also note, this answer is largely okay because the construction of `A` is cheap, and can be constructed directly from a `double`. If the OP's `ABC` is expensive to construct, or can't be fully constructed from a raw `double`, then implicit conversion might be too expensive or not possible. – ShadowRanger Oct 21 '20 at 13:42
  • @ShadowRanger Operator calling a method is my personal practice. Short reasoning: you do not need do any friendship, source and binary compatibility is easier to maintain without restraining `operator+` (in future releases it is possible to alter `operator+` for example to lavage lazy evaluation). I always do that for any operators and finding this very handy. – Marek R Oct 21 '20 at 13:43