Destructor doesn't print line on console

1.8k views Asked by At

I'm using visual studio 2013 and printing some cout commands to test, When i debug my code, the control go inside the destructor of both class but it's not printing cout statement on console.

#include <iostream>  
using namespace std;

class Uni
{
 public:
 ~Uni()
 {
    cout << "I am in Uni Destructor" << endl;
 }

 Uni()
 {
    cout << "I am in Uni Constructor" << endl;
 }

};


class Student: public Uni
{
 public:

 Student()
 {
    cout << "I am in Student Constructor" << endl;
 }
 ~Student()
 {
    cout << "I am in Student Destructor" << endl;
 }



};

int main()
{
  Student s;
  system("pause");
  return 0;
}

Output:

I am in Uni Constructor

I am in Student Constructor

2

There are 2 answers

5
leslie.yao On BEST ANSWER

I suppose you get the output at this point, i.e. after the pause.

int main()
{
  Student s;
  system("pause");

  // here; but s is not destroyed yet
  return 0;
}

But at that point s is still not destroyed. It will be destroyed when get out of the scope where it's declared, i.e. when get out of the function main.

You can put s into further scope for testing.

int main()
{
  {
    Student s;
  } // s will be destroyed here

  system("pause");
  return 0;
}
0
Bernd Colve On

Your Code looks fine, cout ist a buffered console output stream object instance: are you sure that your destructor message ist not just buffered to be written after the last closing brace and flush of cout?