ITP

BCA - OOPS and Data Structures

Friend Function

In : BCA Subject : OOPS and Data Structures

A friend function  is a special kind of function that can access the private and protected members  of a class — even though it is not a member  of that class.

Example :

#include <iostream>
using namespace std;

// Step 1: Define the class
class Box {
private:
    double length, width, height;

public:
    // Constructor
    Box(double l, double w, double h) {
        length = l;
        width = w;
        height = h;
    }

    // Step 2: Declare the friend function inside the class
    friend double calculateVolume(Box box);
};

// Step 3: Define the friend function outside the class
double calculateVolume(Box box) {
    return box.length * box.width * box.height;
}

// Step 4: Use in main
int main() {
    Box myBox(3.0, 4.0, 5.0);

    // Call the friend function
    cout << "Volume is: " << calculateVolume(myBox) << endl;

    return 0;
}

About us

A truly open platform where you may ask questions and get answers. We also provide comprehensive and easy-to-understand answers to question papers.  discover...

Site status

Flag Counter

Privacy Policy

Sitemap