Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          friends/situation-4/friends-sit4.cc - Class A and B are mutual friends of each other - problems in this version.Lecture 4 - slide 34 : 40
Program 2

// We want class A and B to be mutual friends of each other.
// A member function in each class uses a private variable in the other.
// Problematic because ma and mb are inlined in the classes:
// Inside class A we use details about class B, which the compiler
// is not aware of yet.

#include <iostream>
#include <string>

class B;


class A{
private:
  double a;

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

  void ma(B &x){
    a += x.b;                      // error: invalid use of incomplete type  struct B
}

  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){
    b += x.a;                      // OK. The details of class a is known here. 
  }

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


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

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

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