Re: variable scope question
So in effect you have two copies, one in your constructor and one in the class.
Perhaps what you should do is delete the one in your constructor so the class scope takes over, then you can use it in other methods.
Re: variable scope question
If you are still confused, after squidge's post, then the simple way say is modify your constructor like this
Code:
//QSpinBox *recordNumberSpinBox = new QSpinBox;
Re: variable scope question
Quote:
Originally Posted by
Santosh Reddy
If you are still confused, after squidge's post, then the simple way say is modify your constructor like this
Code:
//QSpinBox *recordNumberSpinBox = new QSpinBox;
Whats the diffence between the two lines above and should i also leave the QSpinBox *recordNumberSpinBox; in the header ?
Re: variable scope question
The difference is that first line is declaration of a pointer, visible only in current method, that is constructor. The recordNumberSpinBox member variable is not initialized, so you have a crash when trying to access it. If you want to use the spinbox in other methods, you should leave the declaration in the header, and initialize the member variable:
Code:
this
->recordNumberSpinBox
= new QSpinBox();
Consider this example, it's just like your issue:
Code:
class A{
protected:
int var; //member variable, every object of class A has its own var
public:
A(){
this->var = 10; // initializes this object member variable with value 10
int var = 1; // creates local variable named var, visible only in this constructor
std::cout << "var = " << var << ", this->var = " << this->var << "\n";
// prints: var = 1, this->var = 10
}
void method(){
int x = var + 1; // x = 11, because this objects member variable is used
}
};
Re: variable scope question
Leave it in the header file
Re: variable scope question
The first line declares and initialises a variable in the local scope to point at a block of memory. This variable masks any other variable of the same name in a broader scope, e.g. a class member variable or global. The line variable becomes unavailable at the end of the scope enclosing it (although memory remains allocated). The value of the outer variable remains unchanged, i.e. it does not point at the allocated memory afterward. Compilers will sometimes issue a warning that a local variable masks another variable of the same name.
The second line initialises a variable declared at a broader scope.