C++ Question

Yohhan

Senior member
May 17, 2002
263
0
0
I'm learning C++, my background has been Java up to this point.

I have a question about friend functions as they relate to operator overloading. I understand the overloading side of things when it comes to class functions. For example, you can combine operands of different types so long as the leftmost one is of the class type, ie: someObj + 2.5, but you can't do 2.5 + someObj since C++ can't translate that into a function call.

Where I get screwed up is the friend functions. What's the need for it? Can't you just overload the operator again using function overloading for something like this?:
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
The idea of a friend class is for information hiding not operator overloading.

Declaring one class the friend of another allows that one class to access protected variables and functions, while still denying access to the rest of the program.

As a stupid example, imagine only the Queue class has access (via friend) to the SetQueueState function of a QueueItem class.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
friend is useful for operator overloading using global functions. sometimes you just have to overload using global functions, eg in the case of foo + bar where foo is an int and bar is of your class, the operator + has to be a global function, and if u want that to access foo's protected members, it must have friend status

the following is illegal iirc

i'm not sure why it is illegal, maybe because it would make compilation more difficult
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
dighn's example would need to be standalone to work as desired:

// For calls of the form: double * Obj
Obj operator*(double n, Obj & o)
{
// do something
}
 

Calin

Diamond Member
Apr 9, 2001
3,112
0
0
The example is not legal because the C++ operators won't have different number of number of arguments or different priority. The example would have three operands (arguments) instead of the two usuals (two in the paranthesis and the third being the calling object)

Calin