5

is it possible to use a member variable of a class before declaring it? here is my code.

using namespace std;
class Computer

    {
        public:
            Computer()
            {
                processor_speed = 0;
            }
            ~Computer();
            void setspeed (int);
            int getspeed (void);

        private:
            int processor_speed;
    };
    /*Computer::Computer()
    {
        processor_speed = 0;
    } */
    Computer::~Computer()
    {
        cout<<"this is a destructor"<<endl;
    }
    void Computer:: setspeed(int p)
    {
        processor_speed = p;
    }
    int Computer::getspeed(void)
    {
        return processor_speed;
    }

    int main(void)
    {
        Computer obj;
        cout<<"processor speed is "<<obj.getspeed()<<endl;
        obj.setspeed(100);
        cout<<"processor speed is now "<<obj.getspeed()<<endl;
        return 0;
    }

as u can see here i was able to use variable processor_speed before declaring it. i saw a similar question here: Do class functions/variables have to be declared before being used? but i was not able to understand the reason why this code work. Thanks

Community
  • 1
  • 1
Manvendra Singh
  • 586
  • 5
  • 11
  • This is not a duplicate if he specifically lists it in the question and says he does not understand it. –  Jul 30 '16 at 15:40
  • You can declare member variables after you use them in a member function because the function is not running within the class. If the class is listed before the the function is called, it will work. –  Jul 30 '16 at 15:44

1 Answers1

5

Yes, you can do it.

A member variable is in scope for member functions of your class even if it is textually after its first point of use. The compiler translates your code in several "passes". One could think of it as getting all member variables first, and only then translating member functions, with all declarations in place.

Note that this is not allowed for "free-standing" global and static variables inside translation units: a declaration must precede the first use, otherwise you get an error.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523