Back to notes -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    Class A and B are mutual friends of each other - this version is OK.Lecture 3 - slide 30 : 36
Program 3
// Class A and B are mutual friends of each other. A member function
// in each class uses a private variable in the other.
// It is important that the member functions ma and mb are defined
// after both classes. 

#include <iostream>
#include <string>

class B;

class A{
private:
  double a;

public:
  friend class B;
  A(double a):a(a){}

  void ma(B &x);

  void print(){
    std::cout << a << std::endl;
  }
};

class B{
private:
  double b;

public:
  friend class A;
  B(double b):b(b){}

  void mb(A &x);

  void print(){
    std::cout << b << std::endl;
  }
};

void A::ma(B &x){    // Member functions must be defined outside the 
    a += x.b;        // classes
} 

void B::mb(A &x){
    b += x.a;
} 

int main(){
  A aObj(1);
  B bObj(2);

  aObj.ma(bObj);
  bObj.mb(aObj);

  aObj.print();  // 3
  bObj.print();  // 5
}