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;
}
}
class className{
// Other Declarations
friend returnType functionName(arg list);
};
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
// 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;
}
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
// C++ program to demonstrate the working of friend class
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
private:
int numA;
// friend class declaration
friend class ClassB;
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
};
class ClassB {
private:
int numB;
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
// member function to add numA
// from ClassA and numB from ClassB
int add() {
ClassA objectA;
return objectA.numA + numB;
}
};
int main() {
ClassB objectB;
cout << "Sum: " << objectB.add();
return 0;
}
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}