0
votes

Why it is saying incomplete type, why can't I use friend function like this?

#include<iostream>
using namespace std;
class test;
class test2{
    public:
    void outd(test t)
    {
        cout <<t.x<<endl;
        cout<<t.y<<endl;
    }
}; 
class test{

  int x;  
    int y;
    friend void test2::outd(test t);
public:
    test(int x,int y)
    {
        this->x=x;
        this->y=y;
    }

};



int main()
{
    test t(1,2);
    test2 z;
    z.outd(t);
}

error: prog.cpp: In member function 'void test2::outd(test)':

prog.cpp:6:20: error: 't' has incomplete type

void outd(test t)

prog.cpp:3:7: note: forward declaration of 'class test'

class test;

1
Sure you can't use any member variables from test unless the full declaration is seen by the compiler. - πάντα ῥεῖ

1 Answers

2
votes

You must define the method test2::outd after the class test was declared:

#include<iostream>
using namespace std;
class test;
class test2{
  public:
  void outd(test t);
};

Edit (to the comment) This is called Forward declaration

A declaration of the following form class-key attr identifier ;

Declares a class type which will be defined later in this scope. Until the definition appears, this class name has incomplete type. This allows classes that refer to each other and the type given to the class is incomplete class.