Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is forward declaration in c++? [duplicate]

This answer says:

… Finally,

typedef struct { ... } Foo;

declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also can't be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace.

What is forward declaration?

like image 629
lital maatuk Avatar asked Feb 07 '11 20:02

lital maatuk


People also ask

What are forward declarations in C?

In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };

What is the purpose of forward declaration?

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 advantage of forward declaration?

Forward declarations in C++ are useful to save in compile time as the compiler does not need to check for translation units in the included header. Also it has other benefits such as preventing namespace pollution, allowing to use PImpl idiom and it may even reduce the binary size in some cases.

Is forward declaration good practice?

The Google style guide recommends against using forward declarations, and for good reasons: If someone forward declares something from namespace std, then your code exhibits undefined behavior (but will likely work).


2 Answers

Chad has given a pretty good dictionary definition. Forward declarations are often used in C++ to deal with circular relationships. For example:

class B; // Forward declaration

class A
{
    B* b;
};

class B
{
    A* a;
};
like image 161
Fred Larson Avatar answered Oct 02 '22 10:10

Fred Larson


"In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, or a function) for which the programmer has not yet given a complete definition."

-Wikipedia

like image 32
Chad La Guardia Avatar answered Oct 02 '22 09:10

Chad La Guardia