Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incomplete type error , when using friend functions

Tags:

c++

#include <stdio.h>
class B;

class A;

class A
{
    int a;
    friend int B::f();
};


class B
{
    int b;
    class A x;
public:
    int f();
};

int B::f()
{
    // ...
}

main()
{
    class B b;
    b.f();
}

ERRORS:

a.cpp:9: error: invalid use of incomplete type ‘struct B’

a.cpp:2: error: forward declaration of ‘struct B’

The issue cannot be solved by placing definition of B before A as B has an object of type A.

For this example making B a friend class would do, but in my real code I have more member functions in B (so I need alternative solution).

Finally, can somebody give me links that explain what the compiler does when it comes across a forward declaration, declaration, definition.

like image 957
sanoj Avatar asked Apr 23 '26 21:04

sanoj


1 Answers

DefineB before A, and declare a pointer to A as member data of B:

class A; //forward declaration

class B
{
    int b;
    A  *px; //one change here - make it pointer to A
 public:
    int f();

};

class A
{    
    int a;
    friend int B::f();
};

Or, you could make the entire class B a friend of A, that way you don't have to make the member data pointer to A.

class B; //forward declaration

class A
{    
    int a;
    friend class B;
};

class B
{
    int b;
    A   x; //No change here 
 public:
    int f();

};
like image 84
Nawaz Avatar answered Apr 25 '26 13:04

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!