Friend Class In C++ | Friends Class Explained By Real Life Example
Friend Class In C++
What is a friend class?
A friend class is that class that is a friend of any class. BRUH... I mean that as you have a friend which has access to your every private + protected information like what you like in food, who is your gf ๐๐, what is your weakness but only when you declared it as a friend. So as similar to in real life, you can create friends on programming too.
Okay now here is the official definition of friend class -
A friend class is a class that can access the private and protected members of a class in which it is declared as a friend. This is needed when we want to allow a particular class to access the private and protected members of a class.
So here I explained how a friend class explained by a real-life example -
#include <iostream>
using namespace std;
//Here is a class of you where your information is stored
class You
{
private:
char gf_name[200] = "Riya";
bool coward = true;
protected:
int number = 998877;
int bank_balance = 1200;
public:
char yourname[50] = "Xavier";
char address[1000] = "JhumriTalaiya";
//Definig YourFriend As your friend class
friend class YourFriend;
};
//Here is your friend's class
/*YOU HAVE TO CREATE A FUNCTION
WHERE YOU HAVE TO PASS OBJECT OF
ANOTHER CLASS
*/
class YourFriend
{
public:
void talking_in_public(You Your)
{
//Here gf_name is private(i mean very private๐) but YourFriend Can access this
//and can use anywhere he want
cout<<"You Know My Friend's GF Name Is "<<Your.gf_name<<endl;
//Here Your bank_balance is protected . But your idiot friend can use it anywhere he want
cout<<"You Know My Friend Is Very Rich He's Bank Balance Is Rs."<<Your.bank_balance<<endl;
}
};
int main()
{
You xavier;
YourFriend xavier_friend;
xavier_friend.talking_in_public(xavier);
return 0;
}
Output -
You Know My Friend's GF Name Is Riya
You Know My Friend Is Very Rich He's Bank Balance Is Rs.1200
Comments
Post a Comment