Inheritance and Friendship in C++
Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference)
Friendship in C++: Usually, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, a friend class has the access to the protected and private members of the first one. Classes that are ‘friends’ can access not just the public members, but the private and protected members too. (See this article for reference)
Difference between Inheritance and Friendship in C++: 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, the following program prints an error because the show() which is a friend of base class A tries to access private data of derived class B.
prog.cpp: In function ‘void show()’: prog.cpp:19:9: error: ‘int B::y’ is private int y; ^ prog.cpp:31:49: error: within this context cout << "The default value of B::y = " << b.y; ^
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.