Reputation: 604
While reading this post I was wondering why calling a function previously forward-declarated is possible like in this example
int f(int x, int y); // forward declaration
int main()
{
return f(2,3);
}
int f(int x, int y)
{
return x + y;
}
but instantiating or calling a member variable of a class previously forward-declared is not possible like in the example
class Foo; // forward declaration
int main()
{
Foo foo;
return 0;
}
class Foo
{
int x = 3;
};
My thaughts are that a function is just like an address, which is defined when the forward declaration is done (for example f() is assigned 0xABC
). Then when parsing the return f(x,y)
line the compiler just injects that address 0xABC
in the binary code and then later when parsing the declaration of the function the compiler start inputting the instruction starting from address 0xABC
.
However, when parsing the class Foo forward declaration if the compiler assigns to that class to some memory say 0xDEF
, then when it parses Foo foo
it will not know how much space to allocate since all the members of the class were not defined yet so the compiler doesn't know how much space to allocate in total
I don't really know anything about compilers, so is this correct?
Upvotes: 0
Views: 122
Reputation: 13269
Your assumptions are mostly correct, but you don't need to think about how compilers work.
By forward declaring a function, you make its signature available to the rest of the code. This means its name, return value, and parameter types are known, and that's all you need syntactically to call that function.
By forward declaring a class, you only make it known that its name refers to a type. That enables you to use it in various contexts. For example, you can declare (but not define) a function with that class as a parameter type or as the return type. Or you can define a pointer to that class, because the type a pointer points to doesn't matter as long as you don't try to dereference it. Or you can use it as argument to a typename in a template, as long as that template doesn't actually use it (but it could define a pointer to it or declare a function with it as parameter type and so on).
Knowing only that some particular name refers to a class, you cannot deduce anything about its contents (and yes, its size) or how to actually use it.
Upvotes: 1