Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Inheritance and Friendship in C++

  • Difficulty Level : Easy
  • Last Updated : 17 Dec, 2021

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


// CPP Program to demonstrate the relation between
// Inheritance and Friendship
#include <iostream>
using namespace std;
// Parent Class
class A {
    int x;
    A() { x = 0; }
    friend void show();
// Child Class
class B : public A {
    int y;
    B() { y = 0; }
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()
    return 0;


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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!