2

I have a question that may seem too simple but I'd like to understand the answer to anyway.

Example code bellow.


   #include <QtCore/QCoreApplication>
    #include "parent.h"
    #include "childa.h"
    #include "childb.h"

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);

        Parent one;
        ChildA two;
        ChildB three;

        return a.exec();
    }

#ifndef CHILDA_H
#define CHILDA_H

#include <iostream>
#include "parent.h"

using namespace std;

class ChildA : public Parent
{
public:
    ChildA();
    ~ChildA();
};

#endif // CHILDA_H

  #ifndef CHILDB_H
    #define CHILDB_H

    #include <iostream>
    #include "parent.h"

    using namespace std;

    class ChildB : public Parent
    {
    public:
        ChildB();
        ~ChildB();
    };

    #endif // CHILDB_H

#ifndef PARENT_H
#define PARENT_H

#include <iostream>

using namespace std;

class Parent
{
public:
    Parent();
    virtual ~Parent();
};

#endif // PARENT_H

#include "childa.h"

ChildA::ChildA()
{
    cout << "in Child A const\n";
}

ChildA::~ChildA()
{
    cout << "in Child A destructor\n";
}

#include "childb.h"

ChildB::ChildB()
{
    cout << "in Child B const\n";
}

ChildB::~ChildB()
{
    cout << "in Child B destructor\n";
}

#include "parent.h"

Parent::Parent()
{
    cout << "in Parent const\n";
}

Parent::~Parent()
{
    cout << "in Parent destructor\n";
}

Why is it that I don't see the destructors called?
The object variables should go out of scope in main and the destructors should be called, no?

user440297
  • 1,181
  • 4
  • 23
  • 33

1 Answers1

1

Your objects never go out of scope because your application doesn't exist (i.e. you don't go out of scope of the main function). You need to close your application and you do it like so:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Parent one;
    ChildA two;
    ChildB three;
    // This will immediately terminate the application
    QTimer::singleShot(0, &a, SLOT(quit()));
    return a.exec();
}

Note that you can set the timer to execute in a specific amount of time, for the example above I've set it to execute after 0 ms.

If you don't want to close the application, then you can force the scope

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // Force scope
    {
        Parent one;
        ChildA two;
        ChildB three;
    }

    return a.exec();
}
Kiril
  • 39,672
  • 31
  • 167
  • 226
  • So basically a Qt console application does not end when main runs out of instructions to run? – user440297 Nov 20 '12 at 01:21
  • 1
    @user440297 main never "runs out of instructions". Execution is stalled in a.exec() waiting for an event to occur. Since you haven't generated any events (like asking the application to quit) it sits in the QApplication::exec() event loop forever waiting for something to happen. – wjl Nov 20 '12 at 01:52