Pantsuu Pantsuu - 2 months ago 8
C++ Question

Adding up the elements of an array of pointers to integer objects

I am having a tough time doing this.
Basically I have a class called "integer" that's derived from an abstract base class called "Item".
I am trying to add up all the elements of an array of pointers to integer object as follows:

class Item
{
public:
virtual void print() = 0;
virtual string getType() = 0;
virtual Item* add(Item *item) = 0;
};

class integer: public Item {
private:
int data;
public:
integer(int _data): data(_data){;}
void print () {
cout << data << "\n";
}
string getType() {
return "INTEGER";
}
integer* add(Item *item) {
if(this -> getType() != item -> getType()) {
throw "TYPE MISMATCH" ;
}
integer* tempInt = dynamic_cast<integer*>(item);
return new integer(this -> data + tempInt -> data);
}
};

void printAll(Item** items, int n) {
for(int i = 0; i < n; ++i)
items[i] -> print();
}

void addPrintAll(Item ** items, int n) {
Item* p = items[0];
for(int i = 1; i < n; i++) {
p = p -> add(items[i]);
}
p -> print();
}

void main()
{
int n = 10;
Item **integers = new Item*[n];
Item **strings = new Item*[n];

// populate lists
for (int i = 0; i < n; i++)
{
integers[i] = new integer(i);
}

try
{
printAll(integers, n); // print integers
addPrintAll(integers, n); // add integers
}
catch(char *e)
{
cout << e;
}
}


Now on that line in the addPrintAll function:

p = p -> add(items[i]);


I am repeatedly calling the new operator on p without deleting, thus causing memory leaks.
Any better ways of doing this?

Answer

You can implement an operator+=() for the class. In Item it will be undefined:

virtual Item& operator+=(Item& other) = 0;  

In integer class implement it:

Item& operator+=(Item& other) {
    if(other.getType() != getType()) {
        throw "TYPE MISMATCH" ;
    }
    data += dynamic_cast<integer&>(other).data;
    return *this;
}

And in main, inside the try block, use it like this:

    integer sum(0);
    for(int i = 0; i < n; ++i)
        sum += *integers[i];
    sum.print();
Comments