Including header file in class that is a friend

The syntax is:

friend class Class1;

And no, you don't include the header.

More generally, you don't need to include the header unless you are actually making use of the class definition in some way (e.g. you use an instance of the class and the compiler needs to know what's in it). If you're just referring to the class by name, e.g. you only have a pointer to an instance of the class and you're passing it around, then the compiler doesn't need to see the class definition - it suffices to tell it about the class by declaring it:

class Class1;

This is important for two reasons: the minor one is that it allows you to define types which refer to each other (but you shouldn't!); the major one is that it allows you to reduce the physical coupling in your code base, which can help reduce compile times.


To answer Gary's comment, observe that this compiles and links fine:

class X;

class Y
{
    X *x;
};

int main()
{
    Y y;
    return 0;
}

There is no need to provide the definition of X unless you actually use something from X.

Tags:

C++

Class

Friend