C++ | friend keyword | Question 1
Predict the output of following program.
#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
filter_none
(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
Recommended Posts:
- C++ | friend keyword | Question 2
- C++ | Static Keyword | Question 5
- C++ | Static Keyword | Question 6
- C++ | const keyword | Question 5
- C++ | const keyword | Question 5
- C++ | const keyword | Question 3
- C++ | Static Keyword | Question 4
- C++ | Static Keyword | Question 3
- C++ | const keyword | Question 1
- C++ | const keyword | Question 2
- C++ | Static Keyword | Question 2
- C++ | Static Keyword | Question 1
- Can we access private data members of a class without using a member or a friend function?
- restrict keyword in C
- _Generic keyword in C



