In parallel with this question: When should I use the new keyword in C++?
Let’s say I have the following code structure:
class Foo{
private:
int a;
int b;
/* ect */
};
class Bar{
private:
Foo A;
/* ect */
};
int main() {
Bar *b;
b = new Bar();
// call b->methods()
delete b;
};
I know from the link above b is heap (free store) allocated. But what about the contents of A inside class b? Is it safe to assume A also heap allocated?
“On the heap” is, pedantically, a bit of a misnomer. C++ does not dictate the use of a heap, only that objects that are allocated using
neware allocated on the unspecified “free-store”. Anyway…Yes, if
Bhas a member variable of typeAand you instantiate aBusingnewthen all of that object is on the free-store.It’s important to note however that when you do:
B* b = new B;bitself is not on the free-store, but is rather an automatic variable (ie “on the stack”). The thing thatbpoints to is on the free-store. Automatic variables are destroyed when they go out of scope — but the thingbpoints to in this case will not be. If you don’tdelete b;, you’ll get a memory leak.This may be confusing and seem unimportant. Maybe it is confusing, but it isn’t unimportant. The fact that
bis an automatic variable that points to something on the free-store makes possible a very important idiom known as RAII, which is used for things like smart pointers.shared_ptr<B> b(new B);b, here, is still an automatic variable. But whenbgoes out of scope and is destroyed, it takes the thingbpoints to with it. Using smart pointers here will help to eliminate the memory leak created when you didn’tdelete babove.