Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration of struct

Tags:

c++

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?

like image 593
Viku Avatar asked Jun 05 '12 09:06

Viku


People also ask

Can you forward declare struct?

In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).

What is a forward declaration in C?

As others stated before, a forward declaration in C/C++ is the declaration of something with the actual definition unavailable. Its a declaration telling the compiler "there is a data type ABC".

What is forward declaration of a function?

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.

What is the declaration of the struct?

A "structure declaration" names a type and specifies a sequence of variable values (called "members" or "fields" of the structure) that can have different types. An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type.


1 Answers

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.

like image 199
Alok Save Avatar answered Sep 23 '22 10:09

Alok Save