Skip to main content

C++: Am I managing memory the right way?

Also, how would I go about putting my class in another file? Thanks!

#include <iostream>

using std::cout;
using std::endl;

class Array
{

int *arrayPointer;
public:

  Array(int size);
  ~Array(); 

  int get(int index);
  void set(int index, int value);

protected:
  int array[];
  int size;
};

Array::Array(int theSize){
  size = theSize;
  arrayPointer = new int[size]; 
}

Array::~Array(){
  delete[] arrayPointer;
}

int Array::get(int index){
  return *(arrayPointer + index);
}

void Array::set(int index, int value){
  if(index >= size || index < 0){
    cout << "Ooops, index out of bounds" << endl;
  }
  else{
    *(arrayPointer + index) = value;
  }
}

/* Let's see it in action now! */

int main(){
  int size = 3;
  Array array (size);
  array.set(0, 1);
  array.set(1, 2);
  array.set(2,3);
  cout << "Index 0 = " << array.get(0) << endl;
  cout << "Index 1 = " << array.get(1) << endl;
  cout << "Index 2 = " << array.get(2) << endl;
  array.set(4, 3);
  array.set(-1, 2);
}
Breedly
  • 133
  • 2