jazzybazz
jazzybazz

Reputation: 1887

Dynamically allocated array in a class

Here is a class, which is basically an array of numbers on which I want to perform some operations.

class MyClass {
public:
    MyClass() { //constructor
        int * array = new int[n];
        for(int i = 0; i < n; i++) {
            array[i] = i*i;
        }
    } //end constructor
    int displayIthElement(int i) {
        return array[i];
    }
}

I get: error, identifier "array" is undefined in the displayIthElement function. It's as if the array array stops existing outside of the constructor function, which makes no sense. What is the problem?

Thank you very much.

Upvotes: 2

Views: 9077

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124632

It's as if the array array stops existing outside of the constructor function, which makes no sense.

Actually, it's the only behavior that makes any sense at all... this is how the language works.

array is a local variable declared and defined in your constructor. When the constructor exits the pointer variable is destroyed, and you leak the memory it refers to. Memory allocated with new or new [] always requires a corresponding delete or delete [] before its referent goes out of scope. Always.

array should be a member of the class. You're learning, so it's a good idea to figure out how dynamic memory handling works, but in the future, prefer a safe container (i.e., std::unique_ptr, std::vector, etc.) which handles allocation and deallocation for you.

class foo {
public:
  foo() { 
    array = new int[length];
    for(int i = 0; i < length; i++) {
      array[i] = i*i;
    }       
  }
private:
  int *array;  // when does this get deallocated?  Look up RAII
};

Upvotes: 6

Related Questions