Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Operator overloading explanation [duplicate]

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

like image 382
user1772218 Avatar asked Dec 10 '25 20:12

user1772218


1 Answers

The friend keyword grants access to the protected and private members of a class. It is not used in your example because those functions don't need to use the internals of string; the public interface is sufficient.

friend functions are never members of a class, even when defined inside class {} scope. This is a rather confusing. Sometimes friend is used as a trick to define a non-member function inside the class {} 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 becomes this inside the overload function, which can cause confusing bugs. So commutative operators usually should be non-members (friend or not).

like image 88
Potatoswatter Avatar answered Dec 12 '25 10:12

Potatoswatter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!