Search code examples
c++qtmultiple-inheritance

What to pass in a class constructor with multiple inheritance?


I just started learning C++ and QT, sorry if this is a weird question.

I inherit a class from two classes, each of which has a constructor. How can I correctly pass parameters to these two constructors?

I have first class - WirelessSensor

class WirelessSensor : public BoxSensor
{
public:
    explicit WirelessSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent = nullptr);
};

And second class - SwitchSensor

class SwitchSensor : public BinarySensor
{
public:
    explicit SwitchSensor(const unsigned int id, const QString &type, const bool &inverted, QObject *parent = nullptr);
};

This is my inherited class - WirelessSwitchSensor.h

class WirelessSwitchSensor : public WirelessSensor, public SwitchSensor
{
public:
    explicit WirelessSwitchSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent = nullptr);
};

But in the WirelessSwitchSensor.cpp file it highlights the error:[https://i.sstatic.net/HQswI.png]

In constructor 'WirelessSwitchSensor::WirelessSwitchSensor(unsigned int, const QString&, const QString&, QObject*)': ..\Test\Sensor\wirelessswitchsensor.cpp:4:47: error: no matching function for call to 'SwitchSensor::SwitchSensor()' : WirelessSensor(id, type, address, parent)

WirelessSwitchSensor.cpp

WirelessSwitchSensor::WirelessSwitchSensor(const unsigned int id,  const QString &type, const QString &address, QObject *parent)
    : WirelessSensor(id, type, address, parent)
{

}

What is the correct way to write a constructor for my inherited class?


Solution

  • It's really simple - you need to call it directly by chaining the initializations in the derived class:

    struct A
    {
        A(int a) { AA=a; }
        int AA;
    };
    
    struct B
    {
        B(std::string b) { BB=b;}
        std::string BB;
    };
    
    struct C : public A, public B
    {
        C(int a, std::string b) 
        :A(a),
        B(b)
        {
    
        }
    };
    

    Try it yourself :)