Open In App

Inheritance and Friendship in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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

C++




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


Output

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;
                                                ^


Last Updated : 17 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads