Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why creating the same class object allowed inside a method in C++

Tags:

c++

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 ?

like image 773
Avi Avatar asked Aug 20 '26 00:08

Avi


1 Answers

(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.

like image 90
HolyBlackCat Avatar answered Aug 21 '26 14:08

HolyBlackCat