Objects allocated on the stack (such as local variables) are destroyed automatically when they go out of scope.
1 2 3 4 5 6 7 8 9 10 11 12
|
void foo() {
Rectangle r1;
std::cout << "I made a rectangle" << std::endl;
} // r1 goes out of scope right here and the destructor for r1 is called implicitly
void foo2() {
if( rand() % 10 == 1 ) {
Rectangle r1;
std::cout << "This is your lucky day; I made a rectangle" << std::endl;
} // r1 goes out of scope right here and the destructor for r1 is called implicitly
std::cout << "Leaving function foo2" << std::endl;
}
|
You will almost never* explicitly call a destructor like this:
The reason being is that rect is obviously not a pointer and therefore not a heap object; it is
either allocated as a global variable or a local variable, both of which will be destroyed
automatically when they go out of scope.
* @olredixsis: You can read this statement without the word "almost".
@experienced folks: Yes, I know the containers do this, hence why the word "almost".
I know that the object is automatically destroyed after you use it. am I right? |
Local variables are destroyed when they goes out of scope.
so the above declaration is not valid? |
It is legal syntax, but you should not do it. (In fact, in your program, as Rectangle is defined,
it won't necessarily even cause you a problem yet, but still, don't do it.)
the thing is I want to destroy objects that I am not going to use so the object
returns to its starting position. |
The statement does not make sense. When an object is destroyed, it goes into non-existence.
A non-existent rectangle is neither at a starting position nor at any other position. Therefore,
you do not need to assign zero to the members of Rectangle in the destructor. (You don't
even need to define a destructor for Rectangle; the default one provided to you by the
compiler will suffice).