1

So, I want something like:

class A{
B member;
};

class B{
A function();
};

No matter in which order I declare them, I get an incomplete type error (and I pretty much understand why). How can I solve this? I don't want to use pointers or to have the function defined outside the B class. Also, declaring them before as

class A; class B;

doesn't seem to work either.

Deanna
  • 23,876
  • 7
  • 71
  • 156
Ioana
  • 343
  • 5
  • 10
  • Why are you asking? Please explain really what you want to do!!! What really are `A` and `B` ??? Perhaps things could be designed differently... What are the data members of `B`? – Basile Starynkevitch Jul 27 '13 at 20:19
  • 1
    Read [this Q&A](http://stackoverflow.com/questions/553682/when-to-use-forward-declaration) about forward declarations and I think you most likely will be able to modify the contents of your class `A` and `B` to work with the forward declaration. – Alexandru Barbarosie Jul 27 '13 at 20:24

2 Answers2

2

No need for class definition when declare a function.

class A;
class B{
A function();
};
class A{
B member;
};
camino
  • 10,085
  • 20
  • 64
  • 115
  • I just realized that what you said works, but I gave a problem when the function in the B class has an A object as an argument. Any suggestion for this? – Ioana Jul 27 '13 at 20:32
  • in the function declaration, class definition is not needed. whether it was used as return by value or used as parameter. – camino Jul 27 '13 at 20:38
1

This order will work:

class A;

class B {
  A function();
};

class A {
  B member;
};
Tavian Barnes
  • 12,477
  • 4
  • 45
  • 118
  • I just realized that what you said works, but I gave a problem when the function in the B class has an A object as an argument. Any suggestion for this? – Ioana Jul 27 '13 at 20:33
  • @loana The solution proposed above is 'forward declaration'. That would work for what you say as well - function in class B has an argument of type A, only if it is a pointer, and not reference. Forward declarations would only work for pointers objects of class which is not yet fully declared. – goldenmean Jul 30 '13 at 08:52
  • I revise my comment: Forward declarations of a class, works if one just wants to use it as a type r argument of a function, which is requirement of OP. But if one wants to declare an object of that type by value or reference, forward declarations will not work and it would give compilation errors. One can only declare a variable as a pointer object to a class, with forward declaration of that class and that class not defined completely. – goldenmean Jul 30 '13 at 15:34