-1
class c
{
public:
    int r;
    int i;
    c(int a = 1, int b = 2)
    {
        r = a;
        i = b;
    }
    friend c operator+(c c1, c c2);...........(1)
};

c operator+(c c1, c c2)
{
    c k;
    k.r = c1.r + c2.r;
    k.i = c1.i + c2.i;
    return k;
}

int main()
{
    c A(2, 4), B(3, 5);
    c D = A + B;
    cout << D.r << " " << D.i;
}

This code will still work without line (1). Then why do we use that?

Then why do we use "friend" word and mention this function in the class? Is there any specific reason?

  • 4
    "_Then why do we use "friend" word and mention this function in the class?_" Do you know what `friend` even does? Your class has no `private` members, hence, yes, `friend`, in your case, is superfluous. – Algirdas Preidžius Feb 04 '21 at 10:46
  • 1
    okay, I got it. If I don't write friend then the variables need to be public or I'd access them using get function (defined by the user) – Harshit Feb 04 '21 at 11:07

2 Answers2

2

Marking a class or function as a friend enables the friend to access all of the members, restriction free. So if we declare that a certain function is a friend of a class, that function will be able to access all of its members.

In your case, the operator overload c operator+(c c1, c c2) can access all members of c. But still you don't have any private, not protected members. So it's pointless.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
D-RAJ
  • 3,263
  • 2
  • 6
  • 24
0

In C++, overloaded operators can generally be implemented either as a member function(Inside the class declaration) or as non-member functions(Outside the class declaration).

Operators that are implemented as non-member functions are sometimes friend of their operand’s type.

  1. This code will still work without line (1). Then why do we use that?

Answer:- So by removing line (1) you are giving all the work to non-member.

For more info:- What are the basic rules and idioms for operator overloading?

  1. Then why do we use "friend" word and mention this function in the class? Is there any specific reason?

For this, you have to understand the limitation of the non-member function that it can only access the public data member but what if I want to use access private data member you have to use the friend function because it has all the required permission to do so.

For understanding this we need to change your code a little bit:-

class c
{
    int r;
    int i;

public:
    c(int a = 1, int b = 2)
    {
        r = a;
        i = b;
    }
    friend c operator+(c c1, c c2); // ------(1)
    void print()
    {
        cout << r << " " << i << endl;
    }
};
c operator+(c c1, c c2)
{
    c k;
    k.r = c1.r + c2.r;
    k.i = c1.i + c2.i;
    return k;
}

Now if you remove line(1) error will come "error: 'int c::r' is private within this context" Which mean the non-member function cannot access private data member and you need friend function here.