I get a segmentation fault when the append(int val) function is run, and called polymorphically, but I can't see where the memalloc error is coming from. I'm still new to C++, and run into this problem a lot, but when I do fix it on my own, it's always by happenchance. Any pointer? (No pun intended, or is it :))
IntegerCombination.h
#ifndef INTEGERCOMBINATION_H
#define INTEGERCOMBINATION_H
using namespace std;
class IntegerCombination
{
public:
IntegerCombination();
void append(int Val);
virtual int combine() = 0;
protected:
int* _collection;
int _length;
};
#endif
IntegerCombination.cpp
#include "IntegerCombination.h"
IntegerCombination::IntegerCombination()
{
_length = 0;
}
void IntegerCombination::append(int val)
{
int newValPos = _length; // Stores current length as new position for new
// value
int* temp = _collection; //Stores current array
delete _collection; // Deletes current array
_length++; // Increases the length for the new array
_collection = new int[_length]; // Creates a new array with the new length
for(int i = 0; i < newValPos; i++)
{
_collection[i] = temp[i]; // Allocates values from old array into new array
}
_collection[newValPos] = val; // Appends new value onto the end of the new array
}
Main.cpp
#include "IntegerCombination.h"
#include "ProductCombination.h"
using namespace std;
int main()
{
ProductCombination objProd;
for(int i = 1; i <= 10; i++)
{
objProd.append(i);
}
return 0;
}
Note: The code in ProductCombination.h and ProductCombination.cpp is not entirely relevant, as in the .cpp file, append(int val) is only delegating the append call to the base class in IntegerCombination.h