Open In App

C++ | friend keyword | Question 2

Like Article
Like
Save
Share
Report

Predict the output the of following program.




#include <iostream>
using namespace std;
  
class B;
class A {
    int a;
public:
    A():a(0) { }
    void show(A& x, B& y);
};
  
class B {
private:
    int b;
public:
    B():b(0) { }
    friend void A::show(A& x, B& y);
};
  
void A::show(A& x, B& y) {
    x.a = 10;
    cout << "A::a=" << x.a << " B::b=" << y.b;
}
  
int main() {
    A a;
    B b;
    a.show(a,b);
    return 0;
}


(A) Compiler Error
(B) A::a=10 B::b=0
(C) A::a=0 B::b=0


Answer: (B)

Explanation: This is simple program where a function of class A is declared as friend of class B.

Since show() is friend, it can access private data members of B.

Quiz of this Question


Last Updated : 28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads