I'm building a Qt wrapper for RtMidi. As starting point I created two separate classes QMidiOut and QMidiIn that wrap RtMidiOut and RtMidiIn.
I don't want to duplicate code for the common methods (e.g. openPort, closePort, etc), so I'm planning to derive QMidiOut and QMidiIn from a base class (QMidi) with all the the common methods (of RtMidi).
I cannot use template classes (Q_OBJECT doesn't allow that) and I can't create an RtMidi object in the base class, because its destructor is protected.
QMidiIn class:
#ifndef QMIDIIN_H
#define QMIDIIN_H
#include <QObject>
#include "QMidi.h"
class QMidiIn : public QMidi
{
Q_OBJECT
public:
explicit QMidiIn(QObject *parent = nullptr);
~QMidiIn();
private:
RtMidiIn* rtMidiIn = nullptr;
static void callback( double deltatime, std::vector< unsigned char > *message, void *userData );
};
#endif // QMIDIIN_H
QMidiOut class:
#ifndef QMIDIOUT_H
#define QMIDIOUT_H
#include <QObject>
#include "QMidi.h"
class QMidiOut : public QMidi
{
Q_OBJECT
public:
explicit QMidiOut(QObject *parent = nullptr);
~QMidiOut();
private:
RtMidiOut* rtMidiOut = nullptr;
};
#endif // QMIDIOUT_H
QMidi base class
#ifndef QMIDI_H
#define QMIDI_H
#include <QObject>
#include "RtMidi.h"
class QMidi : public QObject
{
Q_OBJECT
public:
explicit QMidi(QObject *parent = nullptr) : QObject(parent) {};
void openPort( unsigned int portNumber = 0, const QString &portName = "RtMidi" ); // common methods
void closePort(); // common methods
protected:
RtMidi* rtMidi = nullptr;
};
My solution is to create the objects in the derived classes and then assign the pointer of the base class:
QMidiOut constructor:
rtMidiOut = new RtMidiOut();
rtMidi = static_cast<RtMidi*>(rtMidiOut);
QMidIn constructor:
rtMidiIn = new RtMidiIn();
rtMidi = static_cast<RtMidi*>(RtMidiIn);
There is a better way to achieve this? The goal is to write all the common methods in a base class.