Saturday, May 9, 2009

What is friend funcation in c++?

what is the friend funcation?in c++?

What is friend funcation in c++?
Any data which is declared private inside a class is not accessible from outside the class. A function which is not a member or an external class can never access such private data. But there may be some cases, where a programmer will need need access to the private data from non-member functions and external classes. C++ offers some exceptions in such cases.





A class can allow non-member functions and other classes to access its own private data, by making them as friends.





http://www.codersource.net/cpp_tutorial_...
Reply:Declaring a function as "friend" means anything in the same namespace can see it and use it.





"private" means only things in the same class can see or use the function.





"public" means everything can see or use the function.
Reply:its used to use the one classes member variables to use in another class





Friend functions


Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class whichnames them as a friend, as if they were themselves members of that class.





A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.





class mylinkage {


private:


mylinkage * prev;


mylinkage * next;


protected:


friend void set_prev(mylinkage* L, mylinkage* N);


void set_next(mylinkage* L);


public:


mylinkage * succ();


mylinkage * pred();


mylinkage();


};





void mylinkage::set_next(mylinkage* L) { next = L; }





void set_prev(mylinkage * L, mylinkage * N ) { N-%26gt;prev = L; }





Friends in other classes


It is possible to specify a member function of another class as a friend as follows:





class C {


friend int B::f1();


};





class B {


int f1();


};





It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.





class A {


friend class B;


};





Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.

sp

No comments:

Post a Comment