Concept of friend function in c++

Can we write member function of one class as friend of another class ? How

  • Snehal
  • 09 Jul 2018
  • 8646 Views
  • 6 Answers
Your Answer

Yes,we can write member function of one class as friend of another class.
 
#include <iostream.h>
 
class B;
 
class A
{
public:
    void showB(B& );
};
 
class B
{
private:
    int b;
public:
    B()  {  b = 0; }
    friend void A::showB(B& x); // Friend function
};
 
void A::showB(B &x)
{
    // Since show() is friend of B, it can
    // access private members of B
    std::cout << "B = " << x.b+5;
}
 
int main()
{
    A a;
    B x;
    a.showB(x);
    return 0;
}

THE OUTPUT WILL BE
B=5

Object Oriented Programming

Didn't get the answer.
Contact people of Talent-Object Oriented Programming directly by clicking here