Sunday, August 2, 2009

In C++, what is the differences between a member function and a friend function? Which is better and why?

Use a member when you can, and a friend when you have to.





Sometimes friends are syntactically better (e.g., in class Fred, friend functions allow the Fred parameter to be second, while members require it to be first). Another good use of friend functions are the binary infix arithmetic operators. E.g., aComplex + aComplex should be defined as a friend rather than a member if you want to allow aFloat + aComplex as well (member functions don't allow promotion of the left hand argument, since that would change the class of the object that is the recipient of the member function invocation).





In other cases, choose a member function over a friend function.

In C++, what is the differences between a member function and a friend function? Which is better and why?
A friend function doesn't belong to the class exclusively, but is located in a class definition file, not the specification file. A member function does. Also, the syntax is different.





Member function:


object.someFunction()





Friend function:


function(objectOne, objectTwo)
Reply:A member function is a function inside of the class. ie any function u write inside the scope of the class is a member function.





A friend function is an outside (non-member) function, which is declared as a 'friend' of a class and it has access to all the private variables of the class.





You should exercise caution using while using friend funcitons.
Reply:A member function is a part of the class. For instance:


Dog.Bark()





The friend function is not a part of THE class. It is a member of a class that is a "Friend" of THE class. It is declared in the access modifier to be a "Friend" of THE class. For instance:


Cow.Bark()





Friend functions are used to access private members of THE class.





In the example I gave, the COW class is declared to be a friend of the DOG class. Bark() is a private DOG function. COW may access the Bark() function of COW by declaring that it is a friend of DOG.


No comments:

Post a Comment