devxlogo

Circular Pointers

Circular Pointers

Question:
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?

Answer:
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.

See also  lenso.ai - an AI reverse image search platform
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist