1

Possible Duplicate:
When to use forward declaration?
C++ classes with members referencing each other

I am pretty new to C++, and I have a question regarding two structures defined below as shown below. Each struct contains a pointer to the other:

    struct A{
    ...
        ...
    B *ptr;
}

    struct B{
    ...
    ...
    A* ptr;
};

However, since the 2nd structure is defined only after the first, I get a compilation error. Is there a solution for this? I tried to declare the struct separately in header files, but it didn't work. Any help is appreciated! Thanks.

Community
  • 1
  • 1

2 Answers2

3

In C++ in order to have a pointer to a type you don't need complete definition of that type. You can just forward declare it.

struct B;
struct A {
    ...
    struct B* ptr;
};
struct B {
    ...
    struct A* ptr;
};
John Dibling
  • 99,718
  • 31
  • 186
  • 324
BigBoss
  • 6,904
  • 2
  • 23
  • 38
2

Yes, use a forward declaration:

struct B;  //forward declare B
struct A{
    ...
        ...
    B *ptr;
};

struct B{
    ...
    ...
    A* ptr;
};

Since the members are pointers, a full definition isn't required - a declaration is sufficient.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625