I'm at the end of my program, however, my destructor is not working.
Please clarify. I'm sure it's working, it's just not working like you expect.
1 2 3 4 5 6 7 8 9 10 11 12 13
int ObjectOnStack()
{
MyClass a;
return 0; // a's dtor called *after* 0 is returned
}
void ObjectOnHeap()
{
MyClass* b = new MyClass;
delete b; // b's dtor called here, before b's memory is free'd
}
Right at the end of my program the destructor is supposed to call a private function of my class. This private function will show what is left from a soda drink machine.
How are you realizing that the destructor is working?
If you have allocated variables on the heap inside of your class, you need to get rid of them manually with delete or free.
Also, everything on the stack is brought out of existence once it's placed outside of scope. ?There is also a way to free these manually?
// This program demonstrates a destructor.
#include <iostream>
usingnamespace std;
class Demo
{
public:
Demo(); // Constructor prototype
~Demo(); // Destructor prototype
};
Demo::Demo() // Constructor function definition
{ cout << "An object has just been defined, so the constructor"
<< " is running.\n";
}
Demo::~Demo() // Destructor function definition
{ cout << "Now the destructor is running.\n";
}
int main()
{
Demo demoObj; // Declare a Demo object;
cout << "The object now exists, but is about to be destroyed.\n";
return 0;
}
Well, it's common practice that you deallocate memory in the destructor. Say you make a variable in your class like so:
1 2 3 4 5 6 7 8 9
class CQobject
{
public:
CQobject() : pExample(newint) {}
~CQobject() { delete pExample; }
private:
int * pExample;
};
And to follow all this up, this might be a post worthy of mentioning: http://tinyurl.com/m982ae
This states that the destructor is called automatically which is why you almost never see the destructor called manually. And to be honest, I don't know if the object that's called on to the heap is deallocated when the destructor is called since I've never seen it mentioned or happening in code.
Yeah i had the same problem. If you run your program in VC++ then it will keep your program open even when it finishes and you will see that the destructor is working.
The console closes immediately because that is what it should do...
When you close a GUI program, you don't expect its window to hang around until you click the [X] button again... Same with a console application.
When running console applications -- start them at the console. That is, a console application presupposes a pre-existing console from which it was run. Unfortunately, people tend to double-click the console application icon (or execute it from their IDEs), and Windows helpfully activates a new console window for the new console application. Which leads to the need for that obnoxious PAUSE function...
Too bad there is no way to check to see if the application was started via double-click or command prompt.