Ad Code

How we use friend function?

How we use friend function?


C++ provides the friend keyword to do just this. Inside a class, you can indicate that other classes (or simply functions) will have direct access to protected and private members of the class. When granting access to a class, you must specify that the access is granted for a class using the class keyword:

friend class aClass;

Note that friend declarations can go in either the public, private, or protected section of a class--it doesn't matter where they appear. In particular, specifying a friend in the section marked protected doesn't prevent the friend from also accessing private fields.

Here is a more concrete example of declaring a friend:

class Node
{
    private:
    int data;
    int key;
    // ...

    friend class BinaryTree; // class BinaryTree can now access data directly
};
Reactions

Post a Comment

0 Comments