C++ | friend keyword | Question 2

Predict the output the of following program.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


(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



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.