Sunday 15 September 2013

Dynamic array class c++

Dynamic array class c++

I am writing a dynamic array class. I included a copy constructor and
operator= function to allow me to assign one array to another. It works
when I assign arrays of the same length to one another, but when they have
different lengths, I get compiler memory warnings, and/or the code bombs
without executing, depending on whether the lefthand array is larger than
the right-hand array, and vice versa. I have a function that inserts
values to the array, and think that the issue might lie here (note: I had
to comment out the memory deletion inside the destructor to get the code
going).
class Array
{
private:
int * ptr;
int size;
int numElement;
public:
Array();
Array(const int*, int);
Array(const Array&);
~Array();
void setValueAtIndex(int, int);
void insertValueAtEnd(int );
int getArraySize();
const Array& operator=(const Array& );
};
#include "array.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
Array::Array()
{
size = 10;
numElement = 0;
ptr = new int[size];
for (int i = 0; i < size; ++i)
{
ptr[i] = 0;
}
}
Array::Array(const int * ptr_, int size_)
{
size = size_;
numElement = size;
ptr = new int[numElement];
for (int i = 0; i < size; ++i)
{
ptr[i] = ptr_[i];
}
}
Array::Array(const Array& other)
{
size = other.size;
numElement = other.numElement;
if (other.ptr)
{
ptr = new int[numElement];
for(int i = 0; i < size; ++i)
{
ptr[i] = other.ptr[i];
}
if(!ptr)
{
exit(EXIT_FAILURE);
}
}
else ptr = 0;
}
Array::~Array()
{
if(ptr)
{
//delete [] ptr;
//ptr = 0;
}
}
void Array::setValueAtIndex(int a, int b)
{
if(b > size)
{
exit(EXIT_FAILURE);
}
ptr[b] = a;
}
void Array::insertValueAtEnd(int insert)
{
if(numElement == size)
{
size++;
}
ptr[size-1] = insert;
numElement++;
}
int Array::getArraySize()
{
return size;
}
const Array& Array::operator=(const Array& other)
{
if(this != &other)
{
if (ptr)
{
delete [] ptr;
ptr = 0;
}
numElement = other.numElement;
size = other.size;
if(other.ptr)
{
ptr = new int[numElement];
for(int i = 0; i < size; ++i)
{
ptr[i] = other.ptr[i];
}
}
else ptr = 0;
}
return *this;
}

No comments:

Post a Comment