Why operator overloading functions can't be members of class
For example, overloading operator<<
Code:
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
using namespace std;
class String
{
string d_name;
public:
String(string const & s) : d_name(s) {}
vector<String> split(string const & delimiter = " ") const
{
vector<string> parts;
boost::split(parts, d_name, boost::is_any_of(delimiter), boost::token_compress_on);
return vector<String>(parts.begin(), parts.end());
}
friend ostream & operator<<(ostream & out, String & obj); // making it as friend function for the convinience of accessing private data members
};
ostream & operator<<(ostream & out, String & obj)
{
return out << obj.d_name << endl; // If not a friend, obj.getName(): string const & getName() const { return d_string; }
}
int main()
{
String s{"This is a test string"};
vector<String> v = s.split();
vector<String>::iterator it;
for(it = v.begin(); it != v.end(); ++it)
cout << *it << endl;
}
Why is the ostream & operator<<(ostream & out, String & obj) cannot be a member function?
I mean, I don't understand the rule that - "operators << and >>, whose left operands are stream classes from the standard library which you cannot change". Kindly help me understand this.
Thanks.
Re: Why operator overloading functions can't be members of class
Non-static member functions require an instance of the class, which gets implicitly passed as the first argument when the function is called (sort of like Python's "self"). The iostream operator implementation in the standard library doesn't support this. It also needs to live in the std namespace, AFAIK.
There is a good explanation on stackoverflow starting at about the third answer.
Note that the operators don't need to be "friends" if the data they use is exposed through public getter / setter methods of the class.