Overloading Through Friend Function in C++

 Overloading Through Friend Function.

To access the private/protected data of a class
When operator/function logic involves two different classes
When operations must be done outside the class
To allow symmetrical operations (e.g., sum(obj, 5) or sum(5, obj))


Rules of Friend Function Overloading

Rule

Description

1

Friend functions are not members, only declared inside the class

2

They can access private and protected data

3

They can be overloaded like normal functions

4

The definition is given outside the class

5

Function signature must differ


 

Syntax:

friend ClassName operator + (ClassName a, ClassName b);

 

PROGRAM: Overloading Friend Functions

#include <iostream>

using namespace std;

 

class Sample {

private:

    int x;

 

public:

    Sample(int a) {

        x = a;

    }

 

    // Friend function declarations (overloaded)

    friend void show(Sample s);        //version 1

    friend void show(Sample s, int y); //version 2

};

 

// Version–1: only object

void show(Sample s) {

    cout << "Value of x = " << s.x << endl;

}

 

// Version–2: object + extra argument

void show(Sample s, int y) {

    cout << "Sum = " << s.x + y << endl;

}

 

int main() {

    Sample obj(10);

 

    show(obj);        // calls version 1

    show(obj, 20);    // calls version 2

 

    return 0;

}


OUTPUT

Value of x = 10

Sum = 30


Key Points

  • To allow an external function to operate on private data
  • To perform operations between objects of different classes
  • To create multiple versions of a friend function

 

Summary Table

Feature

Friend Function

Friend Function Overloading

Access to private data

Yes

Yes

Member of the class

No

No

Can be overloaded

Yes

Yes

Where defined

Outside class

Outside class

Purpose

controlled access

multiple versions

 

================================================================= 

Post a Comment

0 Comments