Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use superclass constructor in Qt Creator?

As you might know, classes in Qt Creator are part of the project as class.h and class.cpp files. Let's presume that we have two classes A (a.h, a.cpp) and B (b.h, b.cpp), and that B inherits A. How can I use the A's constructor when using B's constructor?

like image 655
andreihondrari Avatar asked Nov 30 '25 20:11

andreihondrari


1 Answers

A's constructor is automatically called when you construct a B.

If you need to pass parameters to A's constructor to have it work correctly explicitly call it in B's constructor:

B::B()
 :A(Blah)
{
}

This would be common when A is QObject and you want the ownership stuff to happen correctly, you'll pass in the parent pointer in B's constructor and pass that onto A's:

B::B(QObject* parent_)
 :A(parent_)
{
}

This is nothing to do with Qt and is a pure C++ concept.

like image 191
LovesTha Avatar answered Dec 06 '25 02:12

LovesTha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!