In the constructor of a class I have I create an array with the needed size like this:
ArrayClass::ArrayClass(int size)
{
Number* nmbr = new Number[size];
}
and
ArrayClass::ArrayClass()
{
Number* nmbr = new Number[2];
}
I also have it specified in the header as
Number* nmbr;
While the creation of the array itself works I can't seem to access it outside of the constructor. It seems like whenever I leave the constructor the variable gets freed from the memory. How do I prevent this so I can use the variable when calling the other functions in the class?
Don't create a new variable. The nmbr in your constructors are different from each other and the one in the header.
If you must use a global (think three times about doing this) declare it as extern, define it in a single TU, and just use
nmbr = new ArrayClass[2];
in your constructors.
Don't forget to clean up the memory or about the rule of three.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With