Search code examples
c++visual-c++dev-c++friend-function

How to resolve "class must be used when declaring a friend" error?


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.


Solution

  • 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{};