Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading