Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C++ | friend keyword | Question 1

  • Difficulty Level : Basic
  • Last Updated : 28 Jun, 2021

Predict the output of following program.

#include <iostream>
using namespace std;
class A
    int x;
    A() {x = 0;}
    friend void show();
class B: public A
    B() : y (0) {}
    int y;
void show()
    A a;
    B b;
    cout << "The default value of A::x = " << a.x << " ";
    cout << "The default value of B::y = " << b.y;

(A) Compiler Error in show() because x is protected in class A
(B) Compiler Error in show() because y is private in class b
(C) The default value of A::x = 0 The default value of B::y = 0
(D) Compiler Dependent

Answer: (B)

Explanation: Please note that show() is a friend of class A, so there should not be any compiler error in accessing any member of A in show().

Class B is inherited from A, the important point to note here is friendship is not inherited. So show() doesn’t become a friend of B and therefore can’t access private members of B.

Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!