'Friend function inside class and outside class, what difference does it make?

#include<iostream.h>
#include<conio.h>
class time
{
    private:
        int dd,mm,yy;
    public:
        friend istream & operator >>(istream &ip,time &t)
        {
            cout<<"\nEnter Date";
            ip>>t.dd;
            cout<<"\nEnter Month";
            ip>>t.mm;
            cout<<"\nEnter Year";
            ip>>t.yy;
            return ip;
        }
        friend ostream & operator <<(ostream &op,time &t)
        {
            op<<t.dd<<"/"<<t.mm<<"/"<<t.yy;
            return op;
        }

        void validate();
};

void time::validate()
{
}
int main()
{
    clrscr();
    time t1;
    cin>>t1;
    cout<<t1;
    getch();
    return 0;
}

What difference does it make? When I define the friend function outside the class the compiler is giving an error but when I define it inside a class it works perfectly fine.

Note: I am using Turbo C++. I know that's old school, but we are bound to use that.



Solution 1:[1]

The problem is, that you are accessing private members of your class (dd,mm,yy), what is only allowed for functions of that class or friends. So you have to declare the function a friend inside of the class and than it can be implemented outside of the class.

class time
{
private:
    int dd,mm,yy;
public:
    friend istream & operator >>(istream &ip,time &t); // declare function as friend to allow private memeber access
    friend ostream & operator <<(ostream &op,time &t); // declare function as friend to allow private memeber access

    void validate();
};

Now you can write the implementation outside of the class and access private variables.

istream & operator >>(istream &ip,time &t)
{
    cout<<"\nEnter Date";
    ip>>t.dd;
    cout<<"\nEnter Month";
    ip>>t.mm;
    cout<<"\nEnter Year";
    ip>>t.yy;
    return ip;
}

ostream & operator <<(ostream &op,time &t)
{
    op<<t.dd<<"/"<<t.mm<<"/"<<t.yy;
    return op;
}

Solution 2:[2]

Though the friend functions are inside the class it doesn't mean that they are the member functions of the class. So you should not refer the friend function outside of the class by using className::

struct time
{
    int dd = 28, mm = 04, yy = 2022;
    // friend function declaration
    friend ostream& operator <<(ostream& op, const time& t);
    // memeber function declaration
    void validate();
};

void time::validate() // time:: (must bcos it is a member function) 
{
    cout << dd << "/" << mm << "/" << yy << endl;
}

ostream& operator <<(ostream& op, const time& t)  // time:: (should NOT come bcos it is NOT a member function)
{
    op << t.dd << "/" << t.mm << "/" << t.yy << endl;
    return op;
}


int main() {
    time t;
    cout << t;    // 28/4/2022
    t.validate(); // 28/4/2022
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SridharKritha