Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
#includeusing 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 Output
[Error] 'int MyDerivedClass::y' is private [Error] within this context
Advertisements
