BIT153 ยท 2082 ยท 5 marks
Explain friend function and friend class with example.
Explain friend function and friend class with example. [5]
Quick answer
A friend function is a function that is not a member of a class but has access to the private and protected members of that class. It is declared inside the class using the keyword friend.
Friend Function and Friend Class in C++
Friend Function
Key Points:
- It is defined outside the class scope
- It is not called using an object (no
thispointer) - It can access private data of the class directly
Example of Friend Function
#include <iostream>
using namespace std;
class Rectangle {
private:
float length, breadth;
public:
Rectangle(float l, float b) {
length = l;
breadth = b;
}
// Declaring friend function
friend float calculateArea(Rectangle r);
};
// Definition of friend function (outside the class)
float calculateArea(Rectangle r) {
// Accessing private members directly
return r.length * r.breadth;
}
int main() {
Rectangle rect(5.0, 3.0);
cout << "Area = " << calculateArea(rect) << endl;
return 0;
}
Output:
Area = 15
Friend Class
A friend class is a class that is granted access to the private and protected members of another class. When a class is declared as a friend, all member functions of that friend class can access private data of the other class.
Key Points:
- Declared using
friend class ClassName;inside the class - Friendship is not mutual (if A is friend of B, B is not automatically friend of A)
- Friendship is not inherited
Example of Friend Class
#include <iostream>
using namespace std;
class Engine {
private:
int horsepower;
public:
Engine(int hp) {
horsepower = hp;
}
// Declaring Car as a friend class
friend class Car;
};
class Car {
public:
void showEngineDetails(Engine e) {
// Accessing private member of Engine class
cout << "Engine Horsepower: " << e.horsepower << endl;
}
};
int main() {
Engine eng(150);
Car car;
car.showEngineDetails(eng);
return 0;
}
Output:
Engine Horsepower: 150
Summary Table
| Feature | Friend Function | Friend Class |
|---|---|---|
| Type | A standalone function | A complete class |
| Declaration | friend returnType funcName(); | friend class ClassName; |
| Access | Private members of one class | Private members of another class |
| Membership | Not a member of the class | Not a member of the class |
Note: Use of friend functions and classes should be minimized as they break the principle of data encapsulation in Object-Oriented Programming.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.