Q6. Demonstrate Friend Function and Friend Class
Question:
Write program to demonstrate use of friend function and friend class.
My Approach
C++ me friend function aur friend class ek special feature hai jo encapsulation ke principle ko tod kar private/protected data ko access karne dete hain.
- Friend Function: Ek normal function jo kisi class ka friend declare hone par uske private/protected members ko directly access kar sakta hai.
- Friend Class: Agar ek class ko friend declare kar diya jaye, to wo dusri class ke private/protected members ko access kar sakti hai.
Ye real-world scenario me useful hota hai jab hume closely related classes ke beech data share karna ho bina unnecessary getter-setter banaye.
Program Code
File Name: friend_demo.cpp
#include <iostream>
using namespace std;
// ================= Friend Function Demo =================
class Box {
private:
int length;
public:
Box(int l) : length(l) {}
// Friend Function declaration
friend void printLength(Box b);
};
// Friend Function Definition
void printLength(Box b) {
cout << "Length of the box: " << b.length << endl;
}
// ================= Friend Class Demo =================
class Engine {
private:
int horsepower;
public:
Engine(int hp) : horsepower(hp) {}
// Declaring Car as a friend class
friend class Car;
};
class Car {
public:
void showEnginePower(Engine e) {
cout << "Car engine horsepower: " << e.horsepower << " HP" << endl;
}
};
// ================= Main Function =================
int main() {
cout << "=== Friend Function Demo ===" << endl;
Box b1(15);
printLength(b1); // Friend function accessing private member
cout << "\n=== Friend Class Demo ===" << endl;
Engine e1(120);
Car c1;
c1.showEnginePower(e1); // Friend class accessing private member
return 0;
}Sample Input / Output
Output:
=== Friend Function Demo ===
Length of the box: 15
=== Friend Class Demo ===
Car engine horsepower: 120 HPExplanation
-
Friend Function Example
printLength()ek normal function hai lekinBoxclass mefrienddeclare kiya gaya hai.- Isliye wo
Boxke private data memberlengthko directly access kar sakta hai.
-
Friend Class Example
Carclass koEngineclass ke andar friend declare kiya gaya hai.- Is wajah se
CardirectlyEngineke private data memberhorsepowerko access kar pa rahi hai.
Real-Time Relevance
- Friend Function: Example – Agar ek class ke private members ko ek external utility function (like logger or printer) ko access karna ho bina getters banaye.
- Friend Class: Example – Car manufacturing system me
CaraurEngineclosely linked classes hain.Carko engine ki internal details chahiye hoti hain, isliyeCarkoEngineka friend declare kiya jata hai.
Conclusion
Is program me dono concepts clearly demonstrate hote hain:
- Friend Function → private data access karne ke liye ek function.
- Friend Class → ek class ko dusri class ke private/protected data access karne ka adhikar.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live
Last updated on