fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. //secondClass needs to know the type firstClass exists to take it as an argument to the ctor
  6. class firstClass;
  7.  
  8. class secondClass
  9. {
  10. public:
  11. secondClass(int val = 0): value(val){}
  12. secondClass(const firstClass& fc); //Just declare that this function exists
  13.  
  14. int getValue()
  15. {
  16. return value;
  17. }
  18.  
  19. int value;
  20. };
  21.  
  22. class firstClass
  23. {
  24. private:
  25. int value;
  26.  
  27. //Since this function is declared, this works
  28. friend secondClass::secondClass(const firstClass& fc);
  29. public:
  30. firstClass(int val = 0): value(val){}
  31.  
  32. };
  33.  
  34. //Finally, now that firstClass is implemented, we can implement this function
  35. secondClass::secondClass(const firstClass& fc)
  36. {
  37. value = fc.value;
  38. }
  39.  
  40. int main()
  41. {
  42. firstClass fc(5);
  43. secondClass sc(fc);
  44.  
  45. cout<<sc.value;
  46.  
  47. }
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
5