0

Very new to QT but basically I have a class called object and on my GUI is a one button and one text browser. Now in my class object I have one private QString variable called name and its constructor assigns a value (QString) to the variable called name . The object class has one function called QString getName() const; which returns the name:

class object{ private: QString name; public: object(QString name); QString getName()const; }; 

Now in QT in my mainwindow.h file I put

public: object *o; 

and then in the constructor :

object o2("Name"); o = &o2; 

Now I want to call the function void MainWindow::on_pushButton_clicked() and all this function will do is set the text in the text browser to the name variable in my object (which would be "Name" btw) so inside the function I put ui->Console->setText(o->getName()); console being the name of my text browser- when i run the code and click the button its saying that Ive referenced memory and giving an error. Keep in mind I moved ui->Console->setText(o->getName()); to the constructor and it worked perfectly (obviously didnt work when the button was clicked but the text was put in the text browser) so what am I doing wrong here ?

2
  • 1
    o = &o2; BAD. When o2 goes out of scope, it is destroyed, thus any reference to it (from o for example) is Undefined. Commented Mar 24, 2021 at 19:35
  • Though you're using Qt, that's not really related here. The question is about plain C++ usage. Commented Mar 24, 2021 at 19:55

1 Answer 1

0

The pointer (o) outlives the object that it points to (o2). One way to fix it is by allocating new memory for the object:

o = new object("Name"); 

And then you'll need to remember to delete that memory later.

Sign up to request clarification or add additional context in comments.

Comments