aleko said:
I guess I asked more than one question. The original question, about
forward declarations is about situations like this:
struct B; // need to declare B in advance. why?
Not sure what you want to know. If you're looking for rationale for
requiring every name to be defined before it's used the first time,
then you need to ask in comp.std.c++, that's where the *reasons* for
rules of the language are discussed. If you just want to know why
compilers nowadays complain if youi don't provide a forward-declaration,
then the answer is simple: because the language Standard says that
a program that attempts to use a symbol (name, identifier) that was not
previsously declared, is ill-formed.
struct A
{
B* b;
};
struct B
{
...
};
My point is that the forward declaration simply tells the compiler
"I'll tell you about this later." It doesn't give it any concrete
information.
Oh, yes, it does. It says 'B' is a struct. It's not a function, it's
not an object, it's not a macro, it's not a template.
It still doesn't know anything about B's structure. The
compiler should be able to insert its own "I'll need to resolve this
later" declaration upon encountering B* b; in A.
By requiring the declarations to exist before the first use of any
name, the C++ compilers can be made better than other, multi-pass
compilers.
I suppose the reason for requiring not-yet declared types to be
forward declared is to make things easier for the compiler.
Yes, that's right.
This way,
it can parse the unit only once, without having to go back and forth
looking up types (possibly in other units). Does this make sense?
Absolutely.
About the other languages:
Other compiled languages like C#, VB, and Delphi do not require
forward declarations.
I think the issue stems from the fact that C++ does not include type
information in the oject files it produces. This forces the compiler
to rely on header files, which essentially duplicate the function
signatures. That's what I mean by "telling the compiler twice".
It doesn't duplicate anything. You declare your function once, in the
header or directly in the source. Then you use it. There is no "twice"
there anywhere. The function does not have to be defined in the same
translation unit, and that's what's great about C++. I don't have to
recompile all my units if I change the implementation and do not change
the interface because the modules that call my function do not care how
it's implemented. They only need to know the declaration (name, return
value type, and arguments).
V