4

Im trying to make class A a friend of class B.

class B;

class A{
public:
void show(const B&); // ##1## but this one works fine  
B ob;// error incomplete type

};


class B{
public:
int b;
B():b(1){}
friend class A;  

};

so my question why it's incomplete type? I thought that when I did class B it's like a prototype of a function which tell the compile there is a definition somewhere in the code.

also in the code above at ##1## why this is possible ?

jleahy
  • 16,149
  • 6
  • 47
  • 66
AlexDan
  • 3,203
  • 7
  • 30
  • 46

1 Answers1

10

No, that's a forward declaration and does not define a full type. You'll need to have a full definition of B before A, if you want to keep the member as an object and not pointer.

One of the reason for this is that the size of the class B must be known to A, since A's size depends on B.

I suggest you #include "B.h" in A.h.

EDIT: clarification:

struct A;

struct B
{
   A foo();
   void foo(A);
   void foo(A&);
   void foo(A*);

   A* _a;
   A& __a;
   A a;  // <--- only error here
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    Worth noting that the reference is fine, because you don't need to know the details of a type to refer to it. – Flexo May 04 '12 at 09:51
  • @AlexDan references and pointers don't need to know anything about the class in a declaration, other than that it exists. – Luchian Grigore May 04 '12 at 09:52
  • @LuchianGrigore : thanks but even If I change the argument of the function show from show(const B&) to show(const B) it works fine. – AlexDan May 04 '12 at 09:57
  • @AlexDan members can be pointers or references without knowing the complete type, return types and parameter types can be incomplete types. – Luchian Grigore May 04 '12 at 09:59