destructor of class

I have typed the program as:-

class test
{
int x;
public:test(int a)
{
x=a;
}
void print(void)
{
cout<<x;
}
~test()
{
cout<<"destructor";
}
};
void main()
{
test t(1);
t.print();
}

When I compiled and executed the program,it showing only 1. but cout<<destructor is not displayed . Why?
Please help...
Last edited on
I compiled and run the program and output shows
1destructor

Try rebuilding the project
t is destructed at the closing brace of main(). Chances are it was displayed, but the program exited before you chould see it. Consider the following:
1
2
3
4
5
void main()
{   test t(1);
    t.print();
    system ("pause");
}

At the time that "pause" is executed, t has not yet been destructed.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.




Last edited on
I have put getch() in the place of system("pause"). Again I compiled and executed,but there is no change.same output,and no destructor
Run you compiled PE inside of a command shell. This will preserve the output after your application exits.
I have put getch() in the place of system("pause")

That doesn't change when t is destructed (after the getch call).

The destructor is getting called, you're just not seeing it because of when t is being destructed.
Last edited on
1
2
3
4
5
6
7
8
9
int main()  // <- main must return int, not void
{
    {  // <- limit scope of the 'test' object
        test t(1);
        t.print();
    }  //<- t's destructor called here

    // <- pause here to see destructor's message
}



Or do what computergeek said and run from a console to see the output.
Topic archived. No new replies allowed.