Updated: Thanks for the quick replies. It seems that I have posted an older version of the code. Everything remains the same except for the parameterized constructor. There are a few flaws in the code as you can see, but bare in mind that I am not fully completed with this. Currently I am more worried about the array since this is a new concept introduced yesterday. I have tried several different things and researched this for hours. Most of the responses say to just use the vector class but this is for homework which helps us understand memory allocation and dynamic arrays. Currently this is my .cpp and .h file that is giving me problems. Every time the delete (or the clear function) operation is triggered an error occurs that states blahblah.exe has triggered a break point.
MyVector.h
#pragma once
class MyVector
{
private:
int arraySize;
int arrayCapacity;
int* theData;
void grow();
public:
MyVector();
MyVector(int n);
int size() const;
int capacity() const;
void clear();
void push_back(int n);
int& at(int n);
~MyVector();
};
MyVector.cpp
#include "MyVector.h"
#include <iostream>
using namespace std;
MyVector::MyVector()
{
arraySize = 0;
arrayCapacity = 0;
theData = new int[0];
}
MyVector::MyVector(int capacityIn)
{
theData = new int [capacityIn];
arraySize = 0;
arrayCapacity = 0;
}
int MyVector::size() const
{
return arraySize;
}
int MyVector::capacity() const
{
return arrayCapacity;
}
void MyVector::clear()
{
delete [] theData;
theData = nullptr;
}
void MyVector::push_back(int n)
{
if (arrayCapacity==0)
{
arrayCapacity++;
MyVector(arrayCapacity);
}
if (arraySize == arrayCapacity)
{
grow();
MyVector(arrayCapacity);
}
theData[arraySize] = n;
arraySize++;
}
int& MyVector::at(int index)
{
if (index >= 0 && index<arraySize)
{
return (theData[index]);
}
else
{
throw index;
}
}
void MyVector::grow()
{
arrayCapacity = arrayCapacity + arrayCapacity;
}
MyVector::~MyVector()
{
if (theData != nullptr)
{
clear();
}
}