Isn't the lifetime of a dynamic object determined by the programmer. So why is it invalid outside of the if block. I understand that regular objects such as Object obj would be destroyed after the block, but why are dynamic objects destroyed after the block.
The obj is invalid outside of the "if" block because of its scope: It was defined within the "if", therefore, it ceases to exist outside of the containing block.
If you want to use obj inside this function, define it at the top.
why are dynamic objects destroyed after the block.
They are not, they continue to exist beyound scope where they are defined.
However pointer obj is still regular object and would die after leaving scope. As you just lost your last pointer to object, you cannot delete it and you leak memory.
They are not, they continue to exist beyond scope where they are defined.
But isn't Object * obj part of the dynamic object? so if I call obj->name aren't I calling the dynamic object that I declared in the if statement block above.
The pointer is a regular stack object. The thing it points to is in this case, dynamic. Hence the pointer can not be used after its scope, even though the object it pointed to still exists.
No. It is a pointer to some object. Which might be dynamic and might be not.
obj->name aren't I calling the dynamic object that I declared
No. You are accessing some memory location stored in pointer and trying to extract data field. If obj is indee a pointer to valid object, everything is okay. Else you have a problem.
Think about object as Building and pointer as paper with address.
On line 15 you are trying to go to the address written on paper and read name of the building... You would try, if you didn't lost that paper at line 13. Now you have no idea where that building is.
Ok, so how would I go about referencing the new Object that I created in the if statement, if the pointer has been destroyed. I assume new Object is still alive and well in heap memory correct.
I see, so the only way to reference a dynamic object (allocated on the heap) is through a pointer which is created on the stack.
Another question that has been bugging me for a while is
Whats the point of using Object * obj , if Object obj can do the same thing without the risk of a memory leak. The only reason I can think of is the programmer determining the lifetime of the dynamic object. Is there something else I am missing?
Using pointers to the free store/heap should be used only when it is needed (and even then use smart pointers). This is almost exclusively when you need something to last beyond the scope in which it is created, although I have seen people using them when you need to create something huge which won't fit on the stack.