Ask a Teacher



DEFINE FRIEND CLASS WITH SYNTAX & EXAMPLE

A friend class in C++, can access the "private" and "protected" members of the class in which it is declared as a friend. On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared. 

When all the member function of a class can access the private and protected members of another class the former class is called the friend class of the latter one.

friend class ClassName;

Example :

#include <iostream>
 
class B
{
    // B declares A as a friend...
    friend class A;
 
private:
    void privatePrint()
    {
        std::cout << "hello, world" << std::endl;
    }
};
 
class A
{
public:
    A()
    {
        B b;
        // ... and A now has access to B's private members
        b.privatePrint();
    }
};
 
int main()
{
    A a;
    return 0;
}


comments powered by Disqus