Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting constructor from QObject based class

I have a class called MiscData that inherits QObject and has a member variable (a model). And then bunch of other classes that inherit MiscData and reimplement its virtual function to populate the model. So it looks like this:

class MiscData : public QObject
{
    Q_OBJECT
public:
    explicit MiscData(QObject *parent = 0);
    QAbstractItemModel &model();
private:
    virtual void loadData() = 0;
private:
    QStandardItemModel m_Model;
}

and one of the descendant looks like this:

class LogData : public MiscData
{
    Q_OBJECT
public:
    using MiscData::MiscData;
private:
    virtual void loadData() override;
}

I know that I must use an explicit constructor for MiscData because it initializes the model member variable. But I am wondering whether it is safe to use using directive in the derived class to inherit MiscData's constructor like this.

EDIT: Based on the answer it seems to be fine event to use using QObject::QObject in the MiscData too.

like image 254
Resurrection Avatar asked Mar 17 '23 14:03

Resurrection


1 Answers

You can call the base class' constructor in the initializer list.

class LogData : public MiscData
{
    Q_OBJECT
public:
    explicit LogData(QObject *parent = 0) : MiscData(parent) {};
private:
    virtual void loadData() override;
}

where MiscData's constructor should pass parent the to QObject the same way:

class MiscData : public QObject
{
    Q_OBJECT
public:
    explicit MiscData(QObject *parent = 0) : QObject(parent) {};
    QAbstractItemModel &model();
private:
    virtual void loadData() = 0;
private:
    QStandardItemModel m_Model;
}

The constructor's definition can be moved into the .cpp file if you want.

using just makes stuff available and does not call anything.

like image 119
Simon Warta Avatar answered Mar 25 '23 02:03

Simon Warta