3

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.stack.imgur.com/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?

junior_L
  • 41
  • 4
  • Does this answer your question? [What are the rules for calling the base class constructor?](https://stackoverflow.com/questions/120876/what-are-the-rules-for-calling-the-base-class-constructor) – Retired Ninja Sep 06 '22 at 08:12
  • The problem is that you call the default constructor of `SwitchSensor` class which doesn't exist. Add it to the class, otherwise call the `SwitchSensor` constructor with parameters as you do for `WirelessSensor`. – vahancho Sep 06 '22 at 08:12
  • 1
    https://stackoverflow.com/q/1711990/4117728 – 463035818_is_not_an_ai Sep 06 '22 at 08:46
  • 1
    Two important advices: 1. be careful with multiple inheritance, often is better to use the principle "prefer composition over inheritance". 2. In Qt you cannot use multiple inheritance if the second parent it's a QObject with a Q_OBJECT macro due to the moc generation. – Moia Sep 06 '22 at 11:12

1 Answers1

3

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 :)

SimplyCode
  • 318
  • 2
  • 9