-2
  1. according to rule we cant define friend function inside the class
  2. for istream and ostream we always declare friend function (so it is right) in below code

But the problem for 1st point how it can be possible for given code to run successfully ....on GNU (ubuntu) compiler

#include<bits/stdc++.h>

using namespace std;

class dev{
    string str;
    int n;
public:
    friend void operator >>(istream &din,dev &s1)
    {
        din>>s1.str>>s1.n;
    }
    friend void operator <<(ostream &dout,dev &s1)
    {
        dout<<s1.str<<" "<<s1.n;
    }
};

int main()
{
    dev s2;
    cin>>s2;
    cout<<s2;
}
Anton Savin
  • 40,838
  • 8
  • 54
  • 90

1 Answers1

1

According to the C++ Standard (11.3 Friends)

6 A function can be defined in a friend declaration of a class if and only if the class is a non-local class (9.8), the function name is unqualified, and the function has namespace scope.

However it is not visible outside the class until it will be declared in the enclosing namespace.

Nevertheless the compiler can find the function due to the so-called Argument Dependent Lookup.

It is due to the ADL that in your example the operators are called successfully.

For example for this statement

cout<<s2;

the compiler sees that there is used an object of type dev (dev s2;) and seeks the operator in the scope of the class.

Take into account that it is better when the operators return references to the streams. In this case you can combine the operators with other stream operators. For example

friend std::ostream & operator <<( std::ostream &dout, const dev &s1 )
{
    return dout << s1.str << " " << s1.n;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335