0

so I have three instances/object of a class, each has an allocated array in heap, and I wanted to use the overloaded 'operator+' to add all the values of each matching element of the first and second instance of the class, and store the values in the third instance/object of the class, I can only use operator overloading, I have already implemented it using 3 argument function where I pass the 1st,2nd,3rd instances/object and perform the addition directly void add(const collection& a, const collection& b, collection& c), now I need to find a way how to do this using operator overloading to achieve the expression c = a + b and produce the correct output, if it is not clear hopefully the sample code below will explain my question more.

#include <iostream>

class collections
{
    public:
        int* items;
        size_t quantiy;

        collections(size_t n) : quantiy(n) { items = new int[n]; }
        ~collections() { delete []  items; }

        collections operator+(const collections& right_hand)
        {
            collections sum(right_hand.quantiy);
            for(size_t i=0; i<right_hand.quantiy; ++i)
            {
                sum.items[i] = items[i] + right_hand.items[i];
            }
            return sum;
        }
};

int main()
{
    collections a(10);
    collections b(10);
    collections c(10);
    
    for(size_t i=0; i<10; ++i)
    {
        a.items[i] = i*2;
        b.items[i] = (i*i);
    }
    
    std::cout<<"a = ";
    for(size_t i=0; i<10; ++i)
        std::cout<<a.items[i]<<' ';
    std::cout<<'\n';
    
    std::cout<<"b = ";
    for(size_t i=0; i<10; ++i)
        std::cout<<b.items[i]<<' ';
    std::cout<<'\n';

    // a : 0 2 4 6 8 10 12 14 16 18
    // +
    // b : 0 1 4 9 16 25 36 49 64 81
    // =
    // c : 0 3 8 15 24 35 48 63 80 99  <-- what I want to achieve
    
    c = a+b;
    
    std::cout<<"c = ";
    for(size_t i=0; i<10; ++i)
        std::cout<<c.items[i]<<' ';

    return 0;
}
trincot
  • 263,463
  • 30
  • 215
  • 251
  • 2
    It is generally advised to use smart pointers. If you still need a custom solution, it seems like you can introduce the desired logic by defining appropriate copy- and move-assignment operators *(you will [need to have a copy-control](https://en.cppreference.com/w/cpp/language/rule_of_three) anyway)*, with all needed memory management. – rawrex Jul 09 '21 at 05:56

0 Answers0