0

in all my other experiments i have done, my variables go out of scope as intended, but when i put variables in the main method, they don't go out of scope or that's what it seems like because the destructor never gets called:

#include <string> #include <iostream> using namespace std; #define PRINT(s) cout << s #define PRINTLN(s) PRINT(s) << endl class Animal { public: string name; int legs; Animal(string name, int legs) { this->name = name; this->legs = legs; } ~Animal(){ PRINTLN("deleting"); } static Animal createAnimal() { PRINTLN("creating"); return Animal("animal", 4); } }; int main() { PRINTLN("start"); Animal a = Animal::createAnimal();//or Animal a("hello", 5); PRINTLN("end running method"); PRINTLN("end"); system("pause"); return 0; //should print out "deleting" here //because of a going out of scope } 
9
  • 2
    It should print deleting after the return. Run your program from the command line to see that. or press ctrl-f5 to run without debugging on Visual Studio. Commented Feb 3, 2016 at 4:23
  • Where is the includes? Commented Feb 3, 2016 at 4:24
  • That's the problem, it's not printing delete at all Commented Feb 3, 2016 at 4:24
  • 2
    I assume you are on Visual Studio and after the return windows closed the window so fast you did not see the result. That is why I gave you 2 methods to get around that. Commented Feb 3, 2016 at 4:25
  • #include <iostream> and #include <string> Commented Feb 3, 2016 at 4:25

1 Answer 1

0

At the point in your code where you have the comment

//should print out "deleting" here //because of a going out of scope 

"a" isn't out of scope. It will go out of scope as the application terminates. Other similar questions (Are destructors run when calling exit()?) discuss what you can expect when the application terminates.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.