Deleting Objects

Hi guys. I am experimenting with the object orientated programming techniques that c++ has to offer and something crossed my mind when reading about memory leaks.

If I have a class called "outerObject" and inside this class is another class called "innerObject" and I first create an object of type "outerObject" and then inside this object I create an object of type "innerObject". If I then delete "outerObject" will "innerObject" be deleted aswell or would I have to delete "innerObject" from within "outerObject" before deleting "outerObject"?

Thanks in advance.
You need to delete the inner object manually.
Thanks for the reply. Does this mean that if I delete the outer object first, I will loose my reference to the inner object and thus it will be forever hogging up space in my volatile memory?
yes that would be a guaranteed memory leak. Just delete the inner object in the outer objects destructor
It depends on how you allocate memory. If you are dynamically allocating with new, then you must have a matching delete for every call to new.

However if you are just using auto variables there's no need to concern yourself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Inner
{
};

class Outer
{
  Inner innerObject;
};

int main()
{
  {
    Outer outerObject;  // outer object and inner object both created here
  }  // both inner object and outer object are automatically destroyed here

  // nothing to worry about.
}


If you need to dynamically allocate for whatever reason, then you need to worry about cleanup. In cases like this, you typically need to implement:
- the default ctor
- the copy ctor
- the assignment operator
- the destructor

Failure to implement any of those will result in potential memory leaks if the class is misused:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Inner {};

class Outer
{
private:
  Inner* innerObject;  // a pointer to be dynamically allocated

public:
  Outer()   // default ctor
    : innerObject( new Inner ) { }  // allocate the inner object

  Outer(const Outer& r)  // copy ctor
    : innerObject( new Inner( *r.innerObject ) ) { } // allocate the inner object as a copy of the other one

  Outer& operator = (const Outer& r)  // assignment operator
  {
    *innerObject = *r.innerObject;  // assign the objects, not the pointers
    return *this;
  }

  ~Outer() // dtor
  {
    delete innerObject;
  }
};



As you can see that is considerably more complex -- so I would avoid dynamically allocated unless you really have to.
This was an interesting and helpful read thank you Disch. I definitely prefer the first method :)
Topic archived. No new replies allowed.