C++ | friend keyword | Question 1

Predict the output of following program.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
class A
{
protected:
    int x;
public:
    A() {x = 0;}
    friend void show();
};
  
class B: public A
{
public:
    B() : y (0) {}
private:
    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;
}

chevron_right


(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