- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Inheritance and friendship in C++
In C++, the friendship is not inherited. It means that, if one parent class has some friend functions, then the child class will not get them as friend.
In this example it will generate an error because the display() function is friend of MyBaseClass but not the friend of MyDerivedClass. The display() can access the private member of MyBaseClass.
Example
#include <iostream> using namespace std; class MyBaseClass { protected: int x; public: MyBaseClass() { x = 20; } friend void display(); }; class MyDerivedClass : public MyBaseClass { private: int y; public: MyDerivedClass() { x = 40; } }; void display() { MyDerivedClass derived; cout << "The value of private member of Base class is: " << derived.x << endl; cout << "The value of private member of Derived class is: " << derived.y << endl; } main() { display(); }
Output
[Error] 'int MyDerivedClass::y' is private [Error] within this context
Advertisements