0

I have a following problem:

I have two classes, class no 2 includes an array of objects class no 2 type. Furthermore i need do write a function of class no 2 which would be a friend to class no 1. Something like this:

class1.h :

    class Class1{
    ...
    friend void Class2::foo();
    }

class2.h:

    %include "class1.h"

    class Class2{

    ...
    Class1 * array[10];
    void foo()
    }

The problem is, that in definition of class1, the program dosent recognize yet class2. I cant include class2.h in class1.h, because I would create recoursive inclusion. Any ideas?

karollo
  • 573
  • 8
  • 22
  • Please put a little more effort into your question, like spelling "#include" correctly. –  Feb 06 '17 at 16:35

1 Answers1

0

Use forward declaration:

  • In file class2.h, change #include "class1.h" to class Class1;
  • In file class2.cpp, add #include "class1.h"

You can do this, because Class2 uses a pointer (not an instance) of Class1.

barak manos
  • 29,648
  • 10
  • 62
  • 114
  • Thanks a lot . I tried it, but the other way around, forward declaration of class2 in class1.h file :) – karollo Feb 06 '17 at 16:44
  • @KarolŻurowski: You're welcome :) As long as no actual instance of `Class1` is used within `Class2`, there's no actual need to include the header of `Class1`, since the size and memory layout of this class does not affect the size and memory layout of `Class2`. The pointer is just a pointer - it has a well known size (typically 4 or 8 bytes), and the compiler can infer the size and memory layout of `Class2` without knowing any further details about `Class1`. – barak manos Feb 06 '17 at 16:49