Please consider the below code.

1 #include <QApplication>
2 #include <QLabel>
3 int main(int argc, char *argv[])
4 {
5 QApplication app(argc, argv);
6 QLabel *label = new QLabel("Hello Qt!");
7 label->show();
8 return app.exec();
9 }


Now, I'm abit doubtful about line 5. According to the book(from which I extracted this code), it is said that QApplication in line 5 is a constructor. Now my questions are:

1. Every constructor should have a class (to which it belongs). So where is the class of this constructor?
2. Assuming that there IS a class for this constructor, then why the name of the constructor doesn't matches with the class to which it belongs?? I think that this is the rule for every constructor that the it should share the same name with the class to which it belongs. Here, we can see that the constructor is named QApplication app(argc, argv). [Assuming that the class name is QApplication.

Please clarify my doubts. I have quite basic knowledge of C++. So if I lack any basic points about constructor, I apologize and therefore request you to help me understand those missing points.

Thank You.

Recommended Answers

All 3 Replies

If I rolled a quick "simulation" of these classes as follows, would it help clarify things?

#include <iostream>
#include <string>

class QApplication // real definition probably in <QApplication>
{
public:
    QApplication(int argc, char *argv[])
    {
        std::cout << "QApplication ctor" << "\n";
    }
};

class QLabel // real definition probably in <Qlabel>
{
    std::string msg;
public:
    QLabel(const char *text) : msg(text)
    {
        std::cout << "QLabel ctor" << "\n";
    }
    void show()
    {
        std::cout << "QLabel show(): " << msg << "\n";
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QLabel *label = new QLabel("Hello Qt!");
    label->show();
    return 0;
}

/* my output
QApplication ctor
QLabel ctor
QLabel show(): Hello Qt!
*/

1. Every constructor should have a class (to which it belongs). So where is the class of this constructor?

Probably in #include <QApplication> .

2. Assuming that there IS a class for this constructor, then why the name of the constructor doesn't matches with the class to which it belongs??

What about QApplication app(argc, argv); doesn't match QApplication ?

Allright, thanks, it helped a lot and my first doubt is cleared.

But you said that:

What about QApplication app(argc, argv); doesn't match QApplication

Here, why do we have that extra app. Isin't it supposed to be QApplication(argc, argv) and not QApplication app(argc, argv). What is the role of that app there?

Thanks

Ohhh..... I'm sorry, all doubts cleard, even the 2nd one... I made some REAllY silly misunderstanding.

Anyways thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.