Search code examples
c++classfriend-function

C++ error C2027: use of undefined type 'second' (Friend Class)


I am learning friend functions (C++) but I can not understand why this code does not work. I get this

error: "error C2027: use of undefined type 'second'". (line number 6)

It is just an example of course (useless). I am trying to use a member function of another class as friend (just that function). I find some example in the web. But in one old post here someone said that a member function of another class cannot be friend of a class.. Is this true?

#include<iostream>
using namespace std;
class second;

class test
{
    friend void second::fun(test &);
public:
    int j = 89;
private:
    int t = 12;
};

class second
{
public:
    void fun(test &b)
    {
        cout << "Try " << b.j << endl;
    }
    int a = 29;
private:
    int u = 10;
};

int main()
{
    test b;
    second one;
    one.fun(b);
    return 0;
}

Solution

  • To access second::fun, a complete definition of second is required. You can fix this if you reverse the order in which you define these classes and forward-declare test instead. But again, b.j requires test to be defined, so you'll have to separate and postpone the definition of second::fun:

    #include<iostream>
    using namespace std;
    class test;
    
    class second
    {
    public:
        void fun(test &b); // test must be declared for using a reference to it
        int a = 29;
    private:
        int u = 10;
    };
    
    class test
    {
        friend void second::fun(test &); // second must be defined to access its member
    public:
        int j = 89;
    private:
        int t = 12;
    };
    
    void second::fun(test &b)
    {
        cout << "Try " << b.j << endl;   // test must be defined to access its member
    }
    
    int main()
    {
        test b;
        second one;
        one.fun(b);
        return 0;
    }