| friends/situation-2/friends-sit2.cc - Class A provides friendship to class B. | Lecture 4 - slide 34 : 40 Program 1 |
// Class B is a friend of class A, such that methods in
// class B can access private variables in class A.
// It is important that class A is defined before class B,
// because the details of class A are needed in mb.
#include <iostream>
#include <string>
class B; // forward declaration, B is an incomplete class
class A{
private:
double a;
public:
friend class B; // B must be known here!
A(double a):a(a){}
void ma(){
a += 3.0;
}
void print(){
std::cout << a << std::endl;
}
};
class B{
private:
double b;
public:
B(double b):b(b){}
// x.a is OK because class B is a friend of A,
// and because class A is defined before class B
void mb(A &x){
b += x.a;
}
void print(){
std::cout << b << std::endl;
}
};
int main(){
A aObj(1);
B bObj(2);
aObj.ma();
bObj.mb(aObj);
aObj.print(); // 4
bObj.print(); // 6
}