Skip to content
Related Articles

Related Articles

C++ | friend keyword | Question 2
  • Last Updated : 23 Aug, 2013

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

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :