GeeksforGeeks » C/C++ Programming Questions
friend and inheritance in C++
(3 posts)-
Why does the following program work? show() is not a friend of class B.
#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() { B b; cout << "The default value of A::x = " << b.x; } int main() { show(); return 0; } -
Surprisingly, when I change the program to following, it fails in compilation.
#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(B b) { cout << "The default value of A::x = " << b.x; } int main() { B b; show(b); return 0; } -
X is a member of class A and class A is a friend of show function
Reply
You must log in to post.