I'm somewhat confused about this code I have to work on so I'll just ask for someone to tell me what I did wrong so far. The class declaration is from the course I'm reading, so it stays the same. The implementation is the one I have to write.
// FloatArray.h
#ifndef FLOAT_ARRAY_H
#define FLOAT_ARRAY_H
class FloatArray
{
public:
// Create a float array with zero elements
FloatArray();
// Create a float array with 'size' elements
FloatArray(int size);
// Create a FloatArray from another FloatArray
// -- be sure to prevent memory leaks!
FloatArray(const FloatArray& rhs);
// Free dynamic memory
~FloatArray();
// Define how a FloatArray shall be assigned to another FloatArray --
// be sure to prevent memory leaks!
FloatArray& operator=(const FloatArray& rhs);
// Resize the FloatArray to a new size
void resize(int newSize);
// Return the number of elements of the array
int size();
// Overload bracket operator so client can index
// into FloatArray objects and access the elements
float& operator[](int i);
private:
float* mData; // Pointer to array of floats (dynamic memory)
int mSize // The number of elements in the array.
};
#endif // FLOAT_ARRAY_H
// FloatArray.cpp
#include "FloatArray.h"
#include <iostream>
usingnamespace std;
FloatArray::FloatArray()
{
mSize = 0;
mData = 0;
}
FloatArray::FloatArray(int size)
{
mSize = size;
mData = newfloat[mSize];
mData = 0;
}
FloatArray::FloatArray(const FloatArray& rhs)
{
float* newArray = newfloat[rhs.mSize];
if (rhs.mSize >= mSize)
{
for (int i = 0; i < mSize; ++i)
newArray[i] = rhs.mData[i];
}
else
{
for (int i = 0; i < rhs.mSize; ++i)
newArray[i] = rhs.mData[i];
}
delete[] mData;
mData = newArray;
}
FloatArray::~FloatArray()
{
delete[] mData;
mData = 0;
}
I'm not sure if I'm supposed to create dynamically allocated arrays and then assign them to the mData pointer, or if the mData itself should be used as an array.
Can someone spot my mistake? NOTE: FloatArray.h and FloatArrayDriver.cpp were provided by the course so they must stay the same. The mistakes are obviously in FloatArray.cpp, which I wrote.
Fortunately, I checked for self-assignment in the overloaded assignment operator and it worked. Like this, in case someone actually uses the same course: