Inheritance and friendship
In C++, friendship is not inherited. If a base class has a friend function, then the function doesn’t become a friend of the derived class(es).
For example, following program prints error because show() which is a friend of base class A tries to access private data of derived 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; // Can't access private member declared in class 'B' cout << "The default value of B::y = " << b.y; } int main() { show(); getchar(); return 0; } |
chevron_right
filter_none
Thanks to Venki for the above code and explanation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Multiple Inheritance in C++
- Does overloading work with Inheritance?
- Inheritance in C++
- Difference between Single and Multiple Inheritance in C++
- Difference between Inheritance and Polymorphism
- Implementing upper_bound() and lower_bound() for Ordered Set in C++
- How to flatten a Vector of Vectors or 2D Vector in C++
- Remove odd frequency characters from the string
- Different ways to use Const with Reference to a Pointer in C++
- std::to_address in C++ with Examples
- Program to create Custom Vector Class in C++
- std::is_trivially_copy_constructible in C/C++
- Difference between Python and C++
- tgamma() method in C/C++ with Examples

