If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.
Syntax:
class class_name
{
friend data_type function_name(arguments);
};
In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator.
Characteristics of a Friend function:
- The function is not in the scope of the class to which it has been declared as a friend.
- It cannot be called using the object as it is not in the scope of that class.
- It can be invoked like a normal function without using the object.
- It cannot access the member names directly and has to use an object name and dot membership operator with the member name.
- It can be declared either in the private or the public part.
#include <iostream>
#include <conio.h>
using namespace std;
class Calculator {
private:
int num1, num2;
public:
// Constructor to initialize numbers
Calculator(int n1, int n2) {
num1 = n1;
num2 = n2;
}
// Declare friend function
friend int addNumbers(Calculator calc);
};
int addNumbers(Calculator calc) {
// Accessing private members directly
return calc.num1 + calc.num2;
}
int main() {
Calculator calc(60, 40); // Create an object of Calculator class
// Call friend function to add numbers
cout << "The sum is: " << addNumbers(calc) << endl;
getch();
return 0;
}
Output:
The sum is : 100
No comments:
Post a Comment