Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make class variable available in other scopes? c++

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?

like image 909
Kraffs Avatar asked Nov 19 '25 01:11

Kraffs


1 Answers

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.

like image 175
Luchian Grigore Avatar answered Nov 21 '25 14:11

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!