Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Passing class reference object to another form class



  • Hi all,

    i have a basic question.

    I have a class instance which need to be passed to other classes being constructed tetra_grip_api api;

    I did this in the main

    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        tetra_grip_api api;
    
        api.openSerialPort();
        QObject::connect(api.serial, SIGNAL(readyRead()), &api, SLOT(readData()));
    
        Settings w(&api);
    

    Also, I changed the constructor of the Settings as follows:

     Settings :: Settings ( tetra_grip_api api, QWidget *parent) : QMainWindow(parent)
        , ui(new Ui:: Settings )
    {
    ...
    
    connect(&api, &tetra_grip_api::tetraGripEvent,this, &Settings::eventHandler);
    

    Here I get an error complaining:

    main.cpp:21:18: error: no matching constructor for initialization of 'Settings'
    settings.h:23:6: note: candidate constructor not viable: no known conversion from 'tetra_grip_api *' to 'tetra_grip_api' for 1st argument; remove &
    settings.h:18:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'tetra_grip_api *' to 'const Settings' for 1st argument
    

    I dont understand what's happening, any idea?

    Thanks


  • Lifetime Qt Champion

    @russjohn834 said in Passing class reference object to another form class:

    Settings :: Settings ( tetra_grip_api api, QWidget *parent) : QMainWindow(parent)

    You're passing by value (means copy!), not by reference. Pass a pointer:

    Settings :: Settings ( tetra_grip_api *api, QWidget *parent) : QMainWindow(parent)
    

    The error message says what is wrong.



  • Thank you @jsulm


Log in to reply