Thursday, August 12, 2010

Friend function in C++ Explained

A friend function is a function that can access the private members of a class as though it were a member of that class. In all other regards, the friend function is just like a normal function. A friend function may or may not be a member of another class. To declare a friend function, simply use the friend keyword in front of the prototype of the function you wish to be a friend of the class. It does not matter whether you declare the friend function in the private or public section of the class.

Here is a small snippet for friend function..try it.

class base
{
private:
        int s;
public:
     base()
       {
       cout<<"s value is"<
       }
friend nonmember(base &a);
};


nonmember(base &a)
{
cout<<"s value from class base is"<
}


void main()
{
base p;
nonmember(p);
}





 
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "Friend function in C++ Explained"

Post a Comment