I’m Such a C++ noob and im trying to understand the code im covering better so I built this class to learn the fundamentals of overloading operators as well as push back and pop back functions ie make my own variable array. This is not a class assignment I am just trying to teach myself the code.
This was actually a computer science programming test question that I did and im trying to learn from it just in case they throw something similar at me again. I started out in java and now doing C++.
#include"IntArray.h"
#include<iostream>
using namespace std;
IntArray::IntArray()
{
size=0;
capacity=1;
data = new int[capacity];
cout<<"constructor fired off"<<endl;
}
IntArray::~IntArray()
{
delete [] data;
cout<<"Destructor fired off"<<endl;
}
IntArray::IntArray (const IntArray & m)
{
size=m.size;
capacity=m.capacity;
data= new int[capacity];
cout<<"copy constructor fired off"<<endl;
}
IntArray IntArray::operator= (const IntArray & other)
{
cout<<"operator= fired off"<<endl;
if(this != &other)//comparing the addresses
{
delete [] data;
size= other.size;
capacity = other.capacity;
data = new int[capacity];
for (int index=0; index<size; index++)
{
data[index]=other.data[index];
}
}
return *this;
}
int& IntArray::operator[] (int n)
{
if(n<0||n>=size)
{
cout<<"Array not big enough"<<endl;
return n;
}
IntArray a;
return a[n];
}
IntArray& IntArray::push_back(int n)
{
data[size]=n;
size++;
if(size==capacity)
capacity=capacity*2;
return *this;
}
IntArray& IntArray::pop_back()
{
if(size>0)
size--;
}
double IntArray::average()
{
double sum=0;
int count=0;
for(int index=0; index<size; index++)
{
sum+=data[index];
count++;
}
return sum/count;
}
int IntArray::getSize()
{
return size;
}
int IntArray::getCapacity()
{
return capacity;
}
My h file
#ifndef INTARRAY_H_INCLUDED
#define INTARRAY_H_INCLUDED
class IntArray
{
private:
int size;
int capacity;
int *data;
public:
IntArray();
~IntArray();
IntArray (const IntArray &);
IntArray operator= (const IntArray &);
int& operator[] (int);
IntArray& push_back(int);
IntArray& pop_back();
double average();
int getSize();
int getCapacity();
};
#endif // INTARRAY_H_INCLUDED
This isn’t going to help much but there is too much that is sub optimal for me to go into.
If this a programming exercise then you need come up with a better design really. I would avoid raw pointers with new and delete, look into smart pointers.
If you actually intend to use this, I wouldn’t the standard provides a type that will meet your needs.