Thread: A variable has to be declared before use

  1. #1
    Registered User
    Join Date
    Apr 2014
    Posts
    9

    A variable has to be declared before use

    Hi,

    If a variable has to be declared before use, then why the following code works? Since in the class definition x is declared after its use in f().

    Code:
    #include <iostream>using namespace std;
    
    
    class A
    {
    public:
        int f() { return x; }
        int x = 10;
    };
    
    
    int main() {
        A a;
        cout << a.f() << endl;
        return 0;
    }
    Thanks in advance.

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    If a variable has to be declared before use, then why the following code works? Since in the class definition x is declared after its use in f().
    O_o

    Though greatly simplified, you may think of this as the compiler being required to parse (read) the definition of a class before parsing the definition of function defined within the class definition.

    The behavior is required otherwise the member function `Class Class::Whatever();' could not return a `Class' instance for not knowing enough about `Class' at that point.

    Unfortunately, when you start reaching for templates and `typedef' things get complicated and not all compilers are good enough to smooth out the wrinkles. You are better off developing a habit of defining things before you use them even within classes, but you don't have to... until you do I guess.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. "Variable Or Field Declared Void" And Other Errors
    By Niki Robbers in forum C Programming
    Replies: 7
    Last Post: 03-29-2014, 01:57 AM
  2. declared extra variable, is it wrong?
    By Lincoln_Poh in forum C++ Programming
    Replies: 3
    Last Post: 09-21-2008, 07:48 AM
  3. Replies: 9
    Last Post: 06-09-2008, 09:53 AM
  4. Read multiple data for one declared variable
    By c++dummy in forum C++ Programming
    Replies: 3
    Last Post: 11-04-2007, 02:13 PM
  5. variable-size type declared outside of any function
    By Okiesmokie in forum C++ Programming
    Replies: 7
    Last Post: 03-23-2002, 03:38 PM