Question

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?

Was it helpful?

Solution 2

Try to declare the variable nmbr in the declaration of the class and not in the constructor. Example:

class ArrayClass

{

private: 

Number *nmbr;

public:

ArrayClass();

ArrayClass(int size);

~ArrayClass()

}

ArrayClass::ArrayClass(int size) 

{

this->nmbr = new Number[size];

}

ArrayClass::ArrayClass() 
{

this->nmbr = new Number[2];

}

ArrayClass::~ArrayClass()
{

delete this->nmbr;

}

OTHER TIPS

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.

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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top