C++ overloading addition operator with dynamic array of objects

0

I am doing this assignment for class and we have to use arrays. I need to overload my object which contains an array of another object and I want to concatenate them. Let's say I want to support the overloading for mySecondObj class, I tried something like this but its not working.

    mySecondObj{
    public:
    .
    .   
    .
    .
    mySecondObj operator+(const mySecondObj& rhs);
    private:    
    .
    .   
    .
    .
    myFirstObj** objList;
}

//addition overloading function
mySecondObj mySecondObj::operator + (const mySecondObj& rhs){

    myFirstObj** temp = new myFirstObj*[this->size + rhs.size];

    std::copy(this->JPList,this->JPList + this->size, temp);
    std::copy(rhs.JPList,rhs.JPList + rhs.size, temp + rhs.size);

    delete[] objList;
    objList = temp;
    return *this;
}

from what I understand I am using it as a member function and am modifying the left hand side object.

edit:

    testcode:
mySecondObj test1 = mySecondObj(arr1, arrSize1);
mySecondObj test2 = mySecondObj(arr2, arrSize2);
.
.
.
mySecondObj test3 = test1 + test2;

This is the code im using to test the function, test1 and test2 does what's expected and when I try to add them I get an exit code -1073741819 (0xC0000005)

I've also changed my code

//addition overloading function
mySecondObj mySecondObj::operator + (const mySecondObj& rhs){

    myFirstObj** temp = new myFirstObj*[this->size + rhs.size];

    std::copy(this->JPList,this->JPList + this->size, temp);
    std::copy(rhs.JPList,rhs.JPList + rhs.size, temp + rhs.size);
    
    return mySecondObj(temp,this->size + rhs.size);
}
c++
memory
dynamic
overloading
addition
asked on Stack Overflow Oct 28, 2020 by tofokevin • edited Oct 28, 2020 by tofokevin

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0