Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ | friend keyword | Question 2

Improve Article
Save Article
  • Last Updated : 28 Jun, 2021
Improve Article
Save Article

Predict the output the of following program.

#include <iostream>
using namespace std;
class B;
class A {
    int a;
    A():a(0) { }
    void show(A& x, B& y);
class B {
    int b;
    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;,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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!