Link to home
Start Free TrialLog in
Avatar of KellyJensen
KellyJensen

asked on

Scope rules for class

     I've created a class called "RDAindividual" with get and set properties. I read data from my database, and create a new object "user". What is confusing me is that inside the "while", I can retrieve my data using the get property, but outside the while I cannot...... I get compile errors. I don't understand, I thought that dynamic variables created with "new" were saved in the heap and not garbage collected, or maybe I'm just using the scope resolution operator wrong. What is wrong?

              while(reader->Read())
            {
                  RDAindividual *user = new RDAindividual(
                        Double::Parse(reader->Item[S"item1"]->ToString()),
                  Double::Parse(reader->Item[S"item2"]->ToString()),
                  Double::Parse(reader->Item[S"item3"]->ToString());

                   MessageBox::Show(user->get_RDAItem2().ToString(), S"Test1");  // Inside "while" this works

            } // end while
            reader->Close();
                MessageBox::Show(RDAindividual::user->get_RDAItem2().ToString(), S"Test2"); // Outside "while" get compile  
                                                                                                                                     //  errors
Avatar of AlexFM
AlexFM

Local variable defined inside of {} block is valid only in this block. Exactly like variable defined in the function is valid only in this function. Change this code by the following way:

          RDAindividual *user = null;

          while(reader->Read())
          {
               user = new RDAindividual(
                        Double::Parse(reader->Item[S"item1"]->ToString()),
               Double::Parse(reader->Item[S"item2"]->ToString()),
               Double::Parse(reader->Item[S"item3"]->ToString());

               MessageBox::Show(user->get_RDAItem2().ToString(), S"Test1");  // Inside "while" this works

          } // end while
          reader->Close();

          if ( user != null )    // precaution: recordset may be empty
              MessageBox::Show(user->get_RDAItem2().ToString(), S"Test2");
Avatar of KellyJensen

ASKER

Thank you, I understand better now. I would really like to know how to make my " *user " pointer global, so that I have access to it throughout my program, not just in the form I am currently using. I have a "Global.h" file where I have some integers defined, and then then use "extern int variable_name;" to tell the compiler that the integers are defined elsewhere. Would it be possible to do the same with an object such as " *user "?
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you very much!! You are Gandalf!!