0

Sorry I could not find a better title :) There are two structs in a header file. These structs have members of type another struct. Compiler complains that B is not declared when I declare B obj. So what should I do?

structures.h

struct A
{
    B obj; // B is not declared yet
};

struct B
{
    A obj;
};
Shibli
  • 5,879
  • 13
  • 62
  • 126
  • 1
    You can't do that. You will have to change your classes to hold something that does not require the full definition of the other type. For instance, a reference, a pointer, some smart pointers, containers designed to work with incomplete types... – juanchopanza Apr 01 '14 at 16:22
  • 2
    What would that even *mean*? An instance of A would contain an instance of B would contain an instance of A would contain an instance of A would contain ... ad infinitum. –  Apr 01 '14 at 16:23
  • @juanchopanza: Could you give an example? – Shibli Apr 01 '14 at 16:26
  • 1
    Have a look at http://stackoverflow.com/questions/553682/when-to-use-forward-declaration – juanchopanza Apr 01 '14 at 16:26

1 Answers1

0

Creating an object of type not declared will not be possible. Best you can have is pointer to that type.

An example of use would be like:

#include <iostream>

using namespace std;

struct A;

struct B{

    A* obj;

    B(){cout<<"B ctr"<<endl;}
};

struct A{

    B* obj;

    A(){cout<<"A ctr"<<endl;}
};


int main()
{
  B obj1;
  obj1.obj = new A();

  A obj2;
  obj2.obj = new B();

   return 0;
}
Nik
  • 1,294
  • 10
  • 16