When we create an object using new it is allocated on the heap. But, what happens to the members of the class that we are instantiating? For example,
class foo {
Bar x;
Bar *y;
foo() {
x = 10;
y = new Bar();
}
}
Here, x is an object while y is an instance of Bar. Are they both allocated on the heap? So if an object of foo F is created locally inside a method, what will happen to y when F goes out of scope?
Also, if F is created on the heap, when will we conclude that F is dangling (no one pointing to it)? Because, there may be no references to F but there may be references to Y.
Yes.
Nothing – the instance pointed to by “y” will stay put, since you don’t have a destructor to provide your cleanup. It’ll effectively become a memory leak, unless something else references it (and cleans it up later).
It’ll be dangling as soon as nothing points to it directly. Something else pointing to
ydoesn’t change the fact thatFis no longer reachable.This is why you really should use proper finalization in this case. Without a call to
deletematching every call tonew, you will leak memory.