Search code examples
c++classoperator-keywordfriend

C++ Class, What's the difference in friend operator vs outside operator


When we define an operator function inside a class an we also define it inside a class then that function is NOT part of the class.

but also the same task is achived when that function is outside the class and we declare it as a friend inside a class but not define it.

consider this code which have two identical operator definitions where one is inside the class an another ouside the class:

version 1 (inside of a class)

class MyClass
{
    // version 1 inside a class
    friend MyClass&& operator +(MyClass& a, MyClass& b)
    {
        return move(MyClass(a.x + b.x, a.y + b.y));
    }
    int x,y;

public:
    MyClass() {}
    MyClass(int,int){}
};

int main()
{
    MyClass a, b, c;
    c = a + b;
    cin.ignore();
    return 0;
}

version 2 (outside of a class)

class MyClass
{
      friend MyClass&& operator +(MyClass& a, MyClass& b);
    int x,y;

public:
    MyClass() {}
    MyClass(int,int){}
};

MyClass&& operator +(MyClass& a, MyClass& b)
{
    return move(MyClass(a.x + b.x, a.y + b.y));
}

int main()
{
    MyClass a, b, c;
    c = a + b;
    cin.ignore();
    return 0;
}

what's the difference in those two approaches?


Solution

  • At the moment, you are defining MyClass&& operator +(MyClass& a, MyClass& b) twice in the first snippet and once in the second. If you remove the second definition, the two will be semantically equivalent.

    The two will do the same thing. In some cases one may be preferred over the other (for example, the second can be placed in a cpp file and the first may be more natural with templates).

    Note that the first is implicitly marked inline, the second is not.

    (You should be passing MyClass by const reference, though.)