2082 6

BIT153 ยท 2082 ยท 5 marks

Explain friend function and friend class with example.

Explain friend function and friend class with example. [5]

Object Oriented ProgrammingChapter 5: Function Features and Inline FunctionsFriend functions

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 this pointer)
  • 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

FeatureFriend FunctionFriend Class
TypeA standalone functionA complete class
Declarationfriend returnType funcName();friend class ClassName;
AccessPrivate members of one classPrivate members of another class
MembershipNot a member of the classNot 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.