If we make the entire class as a friend the automatically all the member functions of the class become friends.

For class B to be a friend of class A. The class A must explicitly declare class B is its friend in the public section

Simple Program for Friend Class

#include
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
// friend function definition
int addFive(Distance d)
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}

Output:-The value of a in sample2 class :5

Explanation of the program

Here sample1 and sample2 are 2 classes and sample2 is a friend of sample1. Hence, sample2 can access all the private data members and member functions of the sample1 class.

This article is written by our awesome writer
Comments to: Friend Class in C++ with Example

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password