Following is the abstraction of string class.
class string {
public:
string(int n = 0) : buf(new char[n + 1]) { buf[0] = '\0'; }
string(const char *);
string(const string &);
~string() { delete [] buf; }
char *getBuf() const;
void setBuf(const char *);
string & operator=(const string &);
string operator+(const string &);
string operator+(const char *);
private:
char *buf;
};
string operator+(const char *, const string &);
std::ostream& operator<<(std::ostream&, const string&);
I want to know why these two operator overloaded functions
string operator+(const char *, const string &);
std::ostream& operator<<(std::ostream&, const string&);
are not class member function or friend functions? I know the two parameter operator overloaded functions are generally friend functions (I am not sure, I would appreciate if you could enlighten on this too) however my prof did not declare them as friend too. Following are the definitions of these function.
string operator+(const char* s, const string& rhs) {
string temp(s);
temp = temp + rhs;
return temp;
}
std::ostream& operator<<(std::ostream& out, const string& s) {
return out << s.getBuf();
}
Could anyone explain this with a small example, or direct me to similar question. Thanks in Advance.
Regards
The
friendkeyword grants access to theprotectedandprivatemembers of aclass. It is not used in your example because those functions don’t need to use the internals ofstring; thepublicinterface is sufficient.friendfunctions are never members of a class, even when defined insideclass {}scope. This is a rather confusing. Sometimesfriendis used as a trick to define a non-member function inside theclass {}braces. But in your example, there is nothing special going on, just two functions. And the functions happen to be operator overloads.It is poor style to define some
operator+overloads as members, and one as a non-member. The interface would be improved by making all of them non-members. Different type conversion rules are applied to a left-hand-side argument that becomesthisinside the overload function, which can cause confusing bugs. So commutative operators usually should be non-members (friendor not).