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

Class instance is uninitialized



  • Hello fellow QT'ers, this is such a weird error. It's crashing my app on run. I get a C4700 uninitialized local variable used. There's no default constructor as the data comes from an external file. In QML, I'm able to console.log(data.name) and it's value is displayed in the application window. Any ideas?

    Data.h
    ------------------------------------------------------------------------
    class Data : public QObject {
        Q_OBJECT
        Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
    public:
        Data(int number);
        ~Data();
        QString name() const;
    public slots:
        void setName(QString name);
    signals:
        void nameChanged(QString name);
    private:
        QString m_name;
    };
    
    Main.cpp
    ------------------------------------------------------------------------
    void Main::testRun()
    {
        Data* data;
        QString name01 = data->name();
        qDebug() << "111: " << data->name();  *** this is the line that has the error.
    }
    

  • Lifetime Qt Champion

    Hi
    Is this the actual code ?
    You have
    Data* data;
    which is a dangling pointer as data points to nothing valid.
    It has t0 be
    Data* data = new Data;



  • @mrjj My apology, I forgot to mention that Data has no default constructor.

    Data* data = new Data; **** I get the error "no matching constructor for initialization of Data"
    


  • Do you undertand the C++ programming language? Given the class definition as shown, of course its going to fail. If new Data fails, then given the class definition what kind of new won't fail?


  • Lifetime Qt Champion

    Hi
    You always have to initialize a pointer.
    Else it will crash on use.
    Hint:
    There is only one constructor and it takes a parameter :)