Hey everyone I got a quick question. I'm getting back into C++ and was wondering about this
If I have dynamically allocated object:
MyObject* obj = new MyObject();
And it has an array inside as member:
class MyObject 
{
public:
   MyObject();
   ~MyObject();
   float array[16];
   private:
};
will just doing a normal delete:
delete obj;
on the object free up all the memory (including the array)? Or do I need to do something special for that?
Yes, you're doing fine. All the memory of the object will be released.
p.s.: If you also dynamically create memory inside the class, you should release their memories inside the destructor ~MyObject().
For example:
class MyObject
{
public:
    /** Constructor */
    MyObject() : test(new int[100]) {}
    /** Destructor */
    ~MyObject() { delete []test; };  // release memory in destructor 
    /** Copy Constructor */
    MyObject(const MyObject &other) : test(new int[100]){
        memcpy(test, other.test, 100*sizeof(int));
    }
    /** Copy Assignment Operator */
    MyObject& operator= (MyObject other){
        memcpy(test, other.test, 100 * sizeof(int));
        return *this;
    }
private:
    int *test;
};
p.s.2: Extra copy constructor and dopy assignment operator are needed to make it follow Rule of three.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With