[cs23021] C++ question

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Nov 10 17:09:08 EST 2010


> Out of curiosity, why do overloaded operator member functions not need to be
> friend functions? It seems like the assignment overloading member function
> should always be a friend function because it has to access the private
> attributes of the other object. The copy constructor also seems like it
> should be a friend function. It confuses me because they both still work as
> non-friend member functions.

Okay, I did a bit more research on this. Here is a more detailed
explanation.

Indeed, a member function can access the private variables of the
object of the same class even if it is not the object on whom the
method is executed. That is, using member functions comparison can
potentially be coded as follows:


	myclass{
	public:
	   bool equal(myclass)
	private
	   int data;
	};

with the member function definition

       bool myclass::equal (myclass right){
       	  if(data == right.data)
	     return true;
 	  else
	     return false;     
       }

Then the function would be invoked as follows:

      myclass b1, b2;
        ...
      b1.equal(b2);

Note that using friend functions the coding would be

        // class definition
        myclass{
        public:
	   friend bool equal(myclass,myclass)
        private
           int data;
        };

	// function definition	
	bool equal(myclass left, myclass right){
	   if(left.data == right.data)
	      return true;
	   else 
	      return false;
	}


	// invocation
	myclass b1, b2;
	   ...
        equal(b1,b2);

Note that a function may be declared a friend of multiple classes (if
it needs to access private members of more than one class).

What to use is a matter of preference. Operator overloading is usually
coded with member functions. Comparisons or other functions where both
object roles are somewhat the same are coded with friend functions.
That is, syntactically

     equal(b1,b2);    looks a bit more intuitive than 
     b1.equal(b2):

Thanks,
-- 
Mikhail


More information about the cs23021-2 mailing list