I am refreshing cpp after a long gap, trying to understand the operator overloading methods. I tried to overload "operator<<" to output members of object. but I am unable to do so without using friend function. I am looking for a method without using friend function.
here is my class def:
class Add{
private:
int x;
public:
friend ostream& operator<<(ostream& ostr, Add const& rhs); //Method 1
void operator<<(ostream& ostr); //Method 2
};
functions implementations
//Method 1
ostream& operator<<(ostream &ostr, Add const& rhs)
{
ostr<<rhs.x;
return ostr;
}
//Method 2
void Add::operator<<(ostream& ostr)
{
cout<<" using operator<< \n";
ostr<<x;
}
calls from the main function
cout<<Obj_Add; //calls the Method 1
Obj_Add<<cout; //calls the Method 2
Now my question is, I would like to achieve the Method 1 type calls without using the friend function. But do not know, it is possible or not in cpp. I have tried few implementation but all are gives me compile errors. Please help me to understand the point i'm missing here.