Case 1: Main.cpp
class Complex
{
void func()
{
Complex c1; // Creating same class object allowed inside a function. Code builds fine. Why?
}
};
int main()
{
return 0;
}
Case 2: Main.cpp
class Complex
{
Complex c1; // Creating same class object not allowed as data member. Build fails because class incomplete
};
int main()
{
return 0;
}
I know why the case 2 fails to build. But why is the case 1 passing?
I read that the complier complies code from top to down line by line. Should case 1 also not fail for the same reason ?
2
(2) fails because the class it not complete yet at that point (the full list of member variables isn’t known yet, more or less). And also because of common sense, as it would cause an infinite nesting of objects (and infinite memory if you add any other member variable).
(1) Passes because the compiler performs two passes over a class to parse it. The method bodies are processed during the second pass, at which point the class is already complete. Also (1) doesn’t require infinite memory, calling .func()
just creates one more object.
1
Case two fails because an object has to have a finite size in memory. There’s no reason a member function of a class cannot have a local object of the same type. If the object has a finite (not absurd) size, then there’s no reason it can’t be created on the stack when the member function is called.
That object is only created when Complex::func
is called.