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 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?
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: