0

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 Answers1

2

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.

thomas
  • 330
  • 3
  • 10
  • Yes it works!!! Thanks a lot, but may I know the reason why this works ? – curositykiller Oct 21 '18 at 12:17
  • @curositykiller Historically, C and C++ compilers work through the source files in order, so the requirement is that things appear in order. It is usually fine, unless you have circular dependencies (like in this case). In some cases in C++, though, this does not apply. For instance, classes can refer to their own members and methods even if they have not been declared yet. – Acorn Oct 21 '18 at 12:38