4
class two;
class one
{
    int a;
    public:
        one()
        {
            a = 8;
        }
    friend two;
};

class two
{
    public:
        two() { }
        two(one i)
        {
            cout << i.a;
        }
};

int main()
{
    one o;
    two t(o);
    getch();
}

I'm getting this error from Dev-C++:

a class-key must be used when declaring a friend

But it runs fine when compiled with Microsoft Visual C++ compiler.

Mat
  • 202,337
  • 40
  • 393
  • 406
shubhendu mahajan
  • 816
  • 1
  • 7
  • 16

2 Answers2

12

You need

 friend class two;

instead of

 friend two;

Also, you don't need to forward-declare your class separately, because a friend-declaration is itself a declaration. You could even do this:

//no forward-declaration of two
class one
{
   friend class two;
   two* mem;
};

class two{};
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • 1
    thanxx for the help but y i was'nt getting error with visual c++ compiler – shubhendu mahajan Aug 28 '11 at 11:45
  • 3
    @desprado07: Well, because many compilers are not exactly strict with this rule (that the word class or struct be present in the friend declaration). It is however mandated by the standard as per 11.4. The accepted answer to [another question](http://stackoverflow.com/questions/656948/a-class-key-must-be-declared-when-declaring-a-friend) may help you. – Armen Tsirunyan Aug 28 '11 at 11:47
  • 5
    It's allowed to be omitted in C++11 – Johannes Schaub - litb Aug 28 '11 at 11:53
5

Your code has:

friend two;

Which should be:

friend class two;
SoapBox
  • 20,457
  • 3
  • 51
  • 87