Operator assignment overloading with dynamically allocated array

I'm writing a class that contains a array allocated dynamic of floats. I need to implement an assignment operator that is overloaded to assign the contents of one array to another.

Here's what I have so far (the class is called ArrayB):

ArrayB & operator= (const ArrayB & other)
{
if (this != &other)
{
//Logic goes here to assign arrays

}

return *this;
}
}

I'm having problems trying to figure out the logic and code to assign arrays to one another with dynamic allocation. Can someone help me out?
Dynamically allocate space for the copy then use a loop to copy each element from the other array.
Could you please show me an example of the code, specifically using the loop the copy the elements?
Why don't you try yourself first?
Here's what I tried:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ArrayB & operator= (const ArrayB & other)
{
if (this != &other)
{
delete [] arrayN;
elementsInArray = right.size();           //size() returns the size of the array
arrayN = new float[elementsInArray];
for (int 1= 0; i < elementsInArray; i++)
    arrayN[i] = right.arrayN[i];
    
return *this;
}


}


elementsInArray is defined in the private area in my class
Last edited on
Did you write the destructor and the copy constructor yet? If you did, the copy assignment is trivial:

1
2
3
4
5
6
ArrayB& operator=(ArrayB other)
{
    swap(arrayN, other.arrayN);
    swap(elementsInArray, other.elementsInArray);
    return *this;
}
No, I haven't. I thought that I needed to write the assignment operator first so that I could use it in the copy constructor. Is that not correct? Is it the opposite way around, I have to do the constructor first so I can use it in the assignment operator?
Last edited on
you need a destructor in c++ when doing this. also might i suggest vectors?
Topic archived. No new replies allowed.