开发者

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

This question already has answers here: What are forward declarations in C++? (8 answers) Closed 5 y开发者_JAVA技巧ears ago.

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?


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;
};


"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


To the best of my knowledge, in C++ the term "forward declaration" is a misnomer. It's simply a declaration under a fancy name.


A fowrard declaration declares the identifier (puts it in a namespace) before the actual definition. You need forward declaration of structs if you need to use a pointer to the struct before the struct is defined.

In the context of the answer you linked, if you have typedef struct {...} Foo;, you cannot use a pointer to Foo inside the struct or before the end of the typedef statement.

On the other hand you can typedef struct tagFoo Foo; and later struct tagFoo {...};


Forward declaration is needed when a class member uses a reference of another class in it. E.g.:

class AB; // forward declaration
class A {
public:
    int j; 
    void sum(AB a) {
        return a.i + j;
    }
};
class AB{
public:
    int i;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜