I'm struggling with some concepts of object memory allocation in C++.
Suppose we have a class:
class Foo {
public:
Foo();
~Foo() {
delete bar;
}
private:
int* bar = new int(5); //Dynamically allocated with 'new'
}
..and we instantiate this class like so:
int main(void) {
Foo f1(); //Automatically allocated
return 0;
}
..what I would like to know is, after the execution of the main()
function, is the object destructor called, thus releasing the dynamically allocated memory for the bar
variable?
If not, how is it possible to release that memory without being able to call delete f1;
? Do we then always need to also dynamically allocate memory for an object, to be able to call delete for that object? For example:
int main(void) {
Foo f1 = new Foo(5); //Dynamically allocated with 'new'
delete f1; //Releases 'bar' memory by calling destructor
return 0;
}
Many thanks for any information!