209k views
3 votes
Difference between the "member method" and the "friend method" of overloading << operator

A) The friend method is a global function, while the member method is a member function
B) The member method is a global function, while the friend method is a member function
C) Both are member functions with different syntax
D) Both are global functions with different syntax

User Farra
by
8.4k points

1 Answer

3 votes

Final answer:

The difference between a member method and a friend method for overloading the << operator is that the friend method is a global function with access rights to the class, while the member method is a function that is part of the class' interface.

Step-by-step explanation:

The difference between a member method and a friend method for overloading the << operator is as follows:

A) The friend method is a global function that has been given special access to the private and protected members of the class, while the member method is a member function of the class.

Therefore, the correct answer is A) The friend method is a global function, while the member method is a member function.

In the context of operator overloading in C++ programming, when the << operator is overloaded using a member function, the object for which it is called can be passed implicitly as the this pointer. However, when using a friend function, the object must be passed explicitly to the function. Because of this, friend functions are often used to overload the << operator as they can handle the left operand being a different type, such as std::ostream. This is important for chaining calls like std::cout << obj1 << obj2.

User Andrei Astrouski
by
8.1k points