It's probably easiest to see a problem here if you put all the code in one place.
Number *nmbr;
class ArrayClass {
Number *nmbr;
public:
ArrayClass() {
Number *nmbr = new Number[2];
}
};
What you have here is three entirely separate variables at three separate scopes. Each one "hides" any variable of the same name at an outer scope.
This also means that when you initialize nmbr
in your constructor, you're only initializing the variable that's local to the constructor itself. When the ctor returns, that pointer will be discarded, and the memory you allocated will be leaked. Equally bad, the ArrayClass::nmbr
that you (almost certainly) wanted to initialize still isn't initialized.
The nmbr
that's outside the class is nearly the same, but marginally safer in one way: since it's a global, it'll be zero-initialized; since it's a pointer, that means it will be initialized to be a null pointer (so it's not pointing at any data, but at least it's easy to test and know it's not).
To prevent this, you probably want to eliminate the extra definitions of the variable, so all the references to nmbr
refer to the same thing:
class Array {
Number *nmbr;
public:
Array() : numbr(new Number[2]) {}
};
Since this class seems to be doing remote ownership (i.e., it allocates and owns data via the pointer) you need to follow the rule of five (an update to the old rule of three for C++11) or, by strong preference, use a std::vector<Number>
instead, so it can follow the "rule of zero".