Search code examples
c++operator-overloadingoperator-keyworddynamic-arrays

Assignment operator, using a dynamic array


I have a list of pointers to objects. What I want to do is read the list and store each object in a dynamic array of that object type. So I do this:

int size = List.size();  // find how many objects in the list
ClassA* object = new ClassA[size];   // create a dynamic array
int counter = 0;
p = List.begin();   // iterator = begining of the list
while( p != List.end() )
{
    object[counter] = (*p)->operator=(*(*p));
                // called like this as this function is in a separate class
    p++;
    counter++;
}

This appears to be what I want which means I need the assignment operator but I am a bit confused as to what to put in it and I am getting stack overflow errors, here is what I thought I needed to do:

 ClassA ClassA::operator =(const ClassA& source)
 {
     ClassA* newObject;
     newObject = new ClassA;
     newObject = source;
     return newObject;

 }

this is a load of BS I no that but in my head this is what I want it to do but I don't fully understand how I implement it.

If anyone can help or suggest a better way to achieve what I need it would be appreciated.

The reason for doing this is the objects stored on this list are normally iterated through each frame and copied into a temporary object. But the list is not changed during the running of the program, which means I don't need to copy each frame, only once at the start. And I need a dynamic array because I don't know how many objects will be stored in the list.


Solution

  • This could be an operator= implementation:

    ClassA &ClassA::operator =(const ClassA& source) {
        // check for self-assignment
        if(this != &source) {
            // copy instance variables.
            a = source.a; // for example...
        }
        // assignment always returns the lvalue
        return *this;
    }
    

    I don't know your ClassA's instance variables, so you should implement the internal copying.

    On the other hand, when iterating your list, you can copy objects this way:

    object[counter] = (**p);
    

    (**p) returns, first the pointer stored in the iterator, and then dereferences it.