I have a problem with memory allocation in c++. This is my code.
#include <iostream>
using namespace std;
class Animal
{
public:
Animal(void)
{
}
Animal(int weight):itsWeight(weight)
{
}
~Animal(void)
{
}
int GetWeight()
{
return itsWeight;
}
void Display()
{
cout << "Weight: " << itsWeight<< endl;
}
private:
int itsWeight;
};
class ArrayTemplate
{
public:
ArrayTemplate(int size)
{
animals = new Animal[size];
index = 0;
}
//copy constructor
ArrayTemplate(const ArrayTemplate &other)
{
}
~ArrayTemplate(void)
{
//if I delete this animals pointer, I got problem.
delete animals;
}
ArrayTemplate operator [] (const Animal &rAnimal)
{
animals[index] = rAnimal;
index++;
return *this;
}
void Display()
{
for (int i=0; i<index; i++)
{
animals[i].Display();
}
}
private:
//current index.
int index;
Animal * animals;
};
int main(int argc, const char * argv[])
{
ArrayTemplate temp(2);
Animal animal1(20);
Animal animal2(30);
temp[animal1];
temp[animal2];
temp.Display();
}
If I delete *animals pointer, I got this error.
cpp_mock_question1(19849,0x7fff7c3be310) malloc: * error for object 0x7fff5fbff8c0: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug