Menu

Destructor Question

Leslie
2008-10-30
2012-09-26
  • Leslie

    Leslie - 2008-10-30

    I wanted to create a little program to demonstrate constructors and destructors to some students. I am using Dev C++ v.4.9.9.2

    The code looked like this:

    include <iostream>

    using namespace std;

    class Truck
    {
    public:
    Truck();
    ~Truck();
    };

    Truck::Truck()
    {
    cout<<"The Truck constructor has run"<<endl;
    }
    Truck::~Truck()
    {
    cout<<"The Truck destructor has run"<<endl;
    }

    int main()
    {
    Truck TwoTon;
    cout<<"This program demonstrates an object with \n";
    cout<<"a constructor and a destructor"<<endl;
    system("pause");
    return 0;
    }

    The code is pretty straight forward, and it does compile; however, the destructor message never appears. The first two messages do appear in the appropriate order. I was wondering if anyone else had experienced this problem. The point was to demonstrate the order in which the methods/output statements execute.

    Thanks in advance,
    Leslie

     
    • Leslie

      Leslie - 2008-10-31

      Ok, great, thanks. I was wondering if it was actually called before or after the system ("pause");

      I tried putting the code in its own code block, as suggested, with the system("pause"); on the outside and it worked like a charm.

      Thanks so much!

       
    • K.Z.

      K.Z. - 2008-10-31

      Old post I know,
      but try this...

      int main()
      {
      {
      Truck TwoTon;
      cout<<"This program demonstrates an object with \n";
      cout<<"a constructor and a destructor"<<endl;
      }
      system("pause");
      return 0;
      }

      TwoTon's destructor should be called when it leaves it's scope,
      before the destructor wasn't called until after the system("pause") command.

       
  • laxman varada

    laxman varada - 2010-08-16

    hi,

    The first two messages do appear in the appropriate order. I was wondering if
    anyone else had experienced this problem. The point was to demonstrate the
    order in which the methods/output statements execute.

    thanks in advice

    regards,
    phe9oxis,
    http://www.guidebuddha.com

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.