extending class property to main?????

class cplus{
public:
void a(){x=5;}
int x;}
in above class we used variable x in function 'a' where x is not declared above the function 'a'.
it means compiler identifies variable where ever we declare in class and enables us to use the variable before its declaration as we done above.
then why cant we extend this property to main function that is "why the following program shows error?

int main(){e=8;
int e;}
just as compiler identified variable x in above class 'cplus', why cant we make changes so that compiler identifies variable in main function where ever it is declared and allow us to use variable before its declaration?????????????
C++ programs are checked in multiple passes. The compiler takes note of members, and resolves things in the C++.

It shouldn't matter where a member is declared in a class because it is a member of the class. Within function scope, however, variables must be pre-declared. In a class, there is an implicit *this pointer passed, so something like 'x' in the function cplus::a() refers to cplus::x. If you did this:
1
2
3
4
5
6
7
8
9
10
11
class cplus
{
  public:
    void a (void)
    {
      x = 5;
      e = 8;
      int e;
    }
    int x;
};

The same thing that happened in main() in your program would also happen in cplus::a() with my class because 'e' was used before it was declared.
Topic archived. No new replies allowed.