Viku
Viku

Reputation: 2973

Forward declaration of struct

I have a header file a.h and inside that I have declared one structure. The name of that structure is file. Inside file I have 3 members: a, b, c. In a.cpp I have implemented that structure and assigned some values to that structure variable.

Now I have another file b.h. Inside it I have a forward declaration of the structure file. Until this point if I compile it's not showing an error but when I am going to access the variable present in that structure through that b.cpp class it will give an error like "undefined struct".

What am I doing wrong?

Upvotes: 20

Views: 84419

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258698

To access members, a full definition is required. You need to include the header inside b.cpp, not just forward-declare the struct (which yields an incomplete type).

EDIT:

A forward declarations is enough for:

class B;
class C
{
    B& b;
    B* b;
    B foo();
    foo(B b);
};

but not for

class B;
class C
{
    B b;   //ERROR
    B foo()
    {
        B x; //error
        x.whatever(); //error
        return B(); //error
    }
};

Upvotes: 16

Tom Tanner
Tom Tanner

Reputation: 9354

You need to include the definition of your struct where the members are used or the compiler doesn't know what they are.

so if you have in b.cpp, this

   func(mystruct &s)
   {
        s.a = 1;
   }

The compiler is fine until it gets to the assignment. At which point, it tries to find the definition of 'a' inside 'mystruct', and can't find it.

You should #include "a.h" in b.cpp, or possibly, depending on what else is in a.h, you might want a separate header for the structure and include that.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206666

What is the root cause of error?

When you Forward declare a type, the compiler treats it as an Incomplete type.

The forward declaration tells the compiler that the said type exists and nothing more about the particular type.So, You cannot perform any action(like creating objects, or dereferencing pointers to that type) on that type which needs compiler to know its memory layout.

Solution:

You cannot forward declare if you need to deference the structure members, You will need to include the header file in the source file.This would ensure that the compiler knows the memory layout of the type. You will have to design your project accordingly.

Upvotes: 24

Related Questions