Sunday, 14 August 2011

friend class

Friend Class

A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration).

A friend class in C++ can access the data members "private" and "protected" members of the class in some other class which it is declared as a friend keyword.


#include <iostream>
#include<conio.h>
class C2;
class C1
{
    // Declare a friend class
    friend class C2;

    public:
        C1()
                {
                 secret=4;
                }
        void show()
        {
            cout << Secret << endl;
        }
    private:
        int Secret;
};

class C2
{
    public:
        void change( C1& y, int x )
        {
            y.Secret = x;
        }
};

void main()
{
    C1 obj1;
    C2 obj2;
    obj1.printMember();
    obj2.change( obj1, 5 );
    obj1.show();
}

Note:
we declared friend class C2; in the class C1, so we can access Secret in the class C2.

Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.

Note:
 1) Friend of the class can be member of some other class.
    2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND.
    3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object.
    4) Friends are non-members hence do not get “this” pointer.
    5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes.
    6) Friend can be declared anywhere (in public, protected or private section) in the class.

What is Friend Function?

No comments:

Post a Comment