In C++, a friend function is a special function that is allowed to access the private and protected members of a class. Unlike member functions, a friend function is not a part of the class but is declared using the
friend
keyword inside the class definition.
Friend functions are primarily used when two or more classes need to share private or protected data for certain operations.
Here’s how a friend function is declared and implemented:
A friend function is declared inside the class using the
friend
keyword.
class ClassName { private: int privateVar; public: ClassName(int val) : privateVar(val) {} // Declaration of friend function friend void friendFunction(ClassName obj); };
The friend function is implemented outside the class, without the
friend
keyword.
void friendFunction(ClassName obj) { std::cout << "Accessing private member: " << obj.privateVar << std::endl; }
#include <iostream> using namespace std; class Box { private: double length; public: Box(double len) : length(len) {} // Friend function declaration friend double getLength(Box obj); }; // Friend function definition double getLength(Box obj) { return obj.length; } int main() { Box box(10.5); // Accessing private member using a friend function cout << "Length of the box: " << getLength(box) << endl; return 0; }
Length of the box: 10.5
#include <iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i = 0) : real(r), imag(i) {} // Friend function for adding two Complex numbers friend Complex operator+(Complex c1, Complex c2); void display() { cout << real << " + " << imag << "i" << endl; } }; // Friend function definition Complex operator+(Complex c1, Complex c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); } int main() { Complex c1(3, 4), c2(1, 2); Complex c3 = c1 + c2; // Using the friend function cout << "Sum of Complex numbers: "; c3.display(); return 0; }
Sum of Complex numbers: 4 + 6i
Copyrights © 2024 letsupdateskills All rights reserved