+ 11
Forward declarations - differences between functions and classes
Following case: g(); int f() { return g(); } This will work since g has been prototyped, it doesn't need to be defined now. class A; class B { A f() {return A{};} This will not work although A is prototyped - this time, before I define B.f, I need to define A first. Why is this different? Just like f in the former example, method f is not called now; can't it rely on A 'being there when it's needed just like f does in the former example? And doesn't it lead to pain when you have different classes in different files with cpps and hpps separated, and everything relies on the other?
5 Answers
+ 6
I think it's because we're mostly interested in the size of `A` (because behind the scenes we have to allocate/reserve the correct amount of space when handling `A`s), and we can't possibly know that with just a forward declaration.
For example:
class A;
int main() {
A a;
int b; // Where on the stack is b?
}
+ 5
Exactly. When dealing with functions on the contrary size is mostly irrelevant, and we care only about the return type (and parameters).
+ 4
Is "return A{};" an accepted way of invoking the default constructor of A?
So can I assume from the discussion that compilation success depends on knowing the sizes? I.e. forward function declaration succeeds because the size of a function pointer and its return type are known from the prototype, whereas forward class declaration fails compilation if instantion is involved which requires the complete class definition?
0
Class is user define datatype and it is a collection of data mamber and mamber function
Class class name
{
Data members () ;
Mamber function ();
}
In function we write code and also do some operation
Function is use for invoked same data more than one time
- 1
ŁŲ³Ų§Ų§Ų³