The Wayback Machine - https://web.archive.org/web/20231217182315/https://www.geeksforgeeks.org/inheritance-and-friendship-in-cpp/
Open In App
Related Articles

Inheritance and Friendship in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
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;
                                                ^

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 17 Dec, 2021
Like Article
Save Article
Previous
Next
Similar Reads