I\'m trying to understand something in C++. Basically I have this:
class SomeClass {
public:
SomeClass();
private:
int x;
};
SomeClass::
In your case, sc
is allocated on the stack, using the default constructor for SomeClass
. Since it is on the stack, the instance will be destructed upon returning from the function. (This would be more impressive if you instantiated SomeClass sc
within a function called from main
--the memory allocated for sc
would be unallocated upon the return to main
.)
The new
keyword, instead of allocating memory on the run-time stack, allocates the memory on the heap. Since C++ has no automatic garbage collection, you (the programmer) are responsible for unallocating any memory you allocate on the heap (using the delete
keyword), in order to avoid memory leaks.