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

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
  • 245,575
  • 61
  • 446
  • 609
2

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
  • 97,027
  • 28
  • 181
  • 313
BigBoss
  • 6,807
  • 1
  • 20
  • 38