xxxxxxxxxx
class Rectangle {
public:
Rectangle(int width, int height) : width_(width), height_(height) {}
friend int area(const Rectangle& rect);
private:
int width_, height_;
};
int area(const Rectangle& rect) {
return rect.width_ * rect.height_;
}
int main() {
Rectangle rect(3, 4);
int a = area(rect);
return 0;
}
The main function creates a Rectangle object and then calls the area function with the object as its argument. Because the area function is a friend function of the Rectangle class, it has access to the private members of the object and can calculate the area of the rectangle.
By using friend functions in C++, you can provide access to the private and protected members of a class to functions that are not members of the class, while still maintaining the encapsulation of the class's data.
xxxxxxxxxx
class A {
private:
int key;
// give class B access to class A
friend class B;
};
class B {
// new object from class A
A new_a;
void fn(){
// access private value from class B
new_a.key;
}
}
xxxxxxxxxx
class className{
// Other Declarations
friend returnType functionName(arg list);
};
xxxxxxxxxx
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
..
}
class ClassB {
..
}
xxxxxxxxxx
class className {
..
friend returnType functionName(arguments);
..
}
xxxxxxxxxx
// Program to illustrate friend function
#include<iostream>
using namespace std;
class integer
{
int a, b;
public:
void set_value()
{
a=50;
b=30;
}
friend int mean(integer s); //declaration of friend function
};
int mean(integer s)
{
return int(s.a+s.b)/2.0; //friend function definition
}
int main()
{
integer c;
c.set_value();
cout<< "Mean value:" <<mean(c);
return 0;
}
xxxxxxxxxx
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
..
}
class ClassB {
..
}
xxxxxxxxxx
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
..
}
class ClassB {
..
}
xxxxxxxxxx
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
..
}
class ClassB {
..
}
xxxxxxxxxx
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
..
}
class ClassB {
..
}