Home > Backend Development > C++ > Friend Function vs. Member Function for Operator Overloading: When is a Friend Function Preferred for `

Friend Function vs. Member Function for Operator Overloading: When is a Friend Function Preferred for `

DDD
Release: 2025-01-03 04:14:39
Original
750 people have browsed it

Friend Function vs. Member Function for Operator Overloading: When is a Friend Function Preferred for `

Operator Overloading: Friend Function vs. Member Function for "<<"

In C , overloaded operators can be implemented either as friend functions or member functions. When it comes to the stream insertion operator "<<," certain considerations guide the choice between these approaches.

Using a Friend Function

friend ostream & operator<<(ostream & os, const Paragraph& p) {
    return os << p.to_str();
}
Copy after login

This approach is commonly used for stream operators because:

  • It allows access to the stream object (os), which is necessary for performing the stream insertion.
  • It follows the convention of stream operators returning a stream reference for chaining purposes.

Using a Member Function

ostream & operator<<(Paragraph const& rhs);
Copy after login

While it's tempting to think that member functions should be used for all class methods, this approach is not recommended for the "<<" operator for several reasons:

  • You cannot access the stream object (os) from a member function.
  • You would need to manually call the "to_str" method in the member function, which is redundant and error-prone.
  • It's not conventional for stream operators to be member functions.

Example

Consider the following class:

class Paragraph {
    std::string m_para;

public:
    Paragraph(std::string const& init) : m_para(init) {}

    std::string const& to_str() const { return m_para; }
};
Copy after login

Rationale

In this case, using a friend function for the "<<" operator is the preferred choice because:

  • It provides access to the stream object (os) for streaming.
  • It follows the convention of stream operators returning a stream reference.
  • It reduces code duplication and potential errors compared to using a member function.

The above is the detailed content of Friend Function vs. Member Function for Operator Overloading: When is a Friend Function Preferred for `. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template