Jon Trauntvein
Jon Trauntvein

Reputation: 4554

Is it legal to declare a friendship with a forward declared class?

I have successfully constructed something similar to the following code in visual studio 2008:

class OpDevconfigSession;
class DevconfigSession
{
... 
private
   friend class OpDevconfigSession;
};

Again, this works quite well with visual studio. However, if I try to compile the code under g++ version 4.3.2, I get an error message such as:

error: friend declaration does not name a class or function

I know that standards conformance is not Microsoft's forte so I am wondering if the code that I have written breaks with the standard in some way that I do not yet understand. Does anyone have any thoughts?

Thanks

Upvotes: 2

Views: 156

Answers (2)

Arun
Arun

Reputation: 20403

The following work for me in g++ ver 4.4.1.

class OpDevconfigSession;
class DevconfigSession
{
  private:
   friend class OpDevconfigSession;
};

I can't see why this might be illegal.

Upvotes: 1

Steve M
Steve M

Reputation: 8526

Your code snippet is missing a colon after private. After fixing that, it Works For Me™ in g++ (http://codepad.org/XJuyEq9z).

It's also standard - you don't even need the separate forward declaration. See this example from 11.4 of the standard:

class X {
    enum { a=100 };
    friend class Y;
};

class Y {
    int v[X::a];        // OK, Y is a friend of X
};

Upvotes: 7

Related Questions