Circular Pointers

Circular Pointers

I’m trying to make two classes point to one another. I know the syntax is weird, but it’s just to illustrate:

 class x{ y* ptry; }class y{ x* ptrx; }

It won’t compile. I get the error “missing storage class.” How do I get around this?

You need to forward-declare a class before you can create a pointer to it:

 class y; //fwd declarationclass x{ y* ptry; };class y{ x* ptrx; };

Without the forward declaration, the compiler doesn’t recognize y as a class name because the declaration of y hasn’t been seen. A forward declaration instructs the compiler to accept the pointer definition even if it hasn’t seen yet the declaration of y. Note that you don’t need a forward declaration for ptrx because by the time the compiler sees its definition, class x has already been seen.


Share the Post: