1
#include <iostream>

class Object {
public:
    int x;
    Object() { }
    Object(int x) {
        this->x = x;
    }
};

class SomeClass {
public:
    Object array[10];
    int n;
    SomeClass() { n = 0; }
    void insert(Object o) {
        array[n++] = o;
    }
};

int main() {
    SomeClass s;
    Object test = Object(4);
    s.insert(test);
    return 0;
}

I have this example where I pre-allocate an array of objects in SomeClass and then in some other method, main in this example, I create another object and add it to the array in SomeClass

One thing I think I should do is to switch from array[10] to an array of pointers so that I only create objects when I really need to.

But my question is what happens to the memory originally allocated for array[0] when I do "array[n++] = o" replacing it by the new object "o"? does it get de-allocated?

1
  • You should not use an array of pointers. Use a vector if you want a resizeable array. Commented Mar 13, 2016 at 23:05

1 Answer 1

5

No, nothing happens. The object's assignment operator gets invoked, to replace the object.

For this simple class, the assignment operator is the default operator which, more or less, copies each of the object's members, one at a time.

(No need to get into move operators, etc..., just yet)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.