Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use '->' operator to access an object pointer by an pointers?

Tags:

c++

pointers

qt

I am just starting a Qt tutorial, and I am also a beginner level of C++. In the Qt tutorial, there is an example that use statement to set the button's text:

ui->pushButton->setText("Hello");

I understand that we can use -> operator to allow an pointer to access member of class. In this case, pushButton->setText("Hello"), but I just don't understand the meaning of ui->pushButton, I search some answers explained that the ui hold the reference of the pushButton, but how this can be done? pushButton is a pointer to the object, is not a member of the class, can we use -> to put the object address to the ui pointer?

Sorry for my bad English language, I may confused you. I wish someone can give me a clear explanation, thanks in advance.

like image 243
Vito Avatar asked Jul 16 '16 06:07

Vito


2 Answers

The ui pointer is generated from the xml you create with the form editor of QT Creator.

You can find the autogenerated header file in the output directory. For example the main window has a ui_mainwindow.h. This file is created after you run qmake. If you use QT Creator this is done automatically.

Here is an example of an autogenerated ui:

class Ui_MainWindow
{
public:
    QWidget *centralWidget;
    QPushButton *pushButton;
    QMenuBar *menuBar;
    QToolBar *mainToolBar;
    QStatusBar *statusBar;
    ...
};

ui is a Ui_MainWindow * so you can use -> on it to access the members of the Ui_MainWindow class, like pushButton.

pushButton is a QPushButton * so you can use -> on it to access the members of the QPushButton class, like setText().

ui->pushButton->setText("Hello") is equivalent to this:

Ui_MainWindow * ui = new Ui_MainWindow;
...
QPushButton * btn = ui->pushButton;
btn->setText("Hello");

Some corrections:

-> does not allow a pointer to do things :)

-> is just an operator to access members of a class or struct, and must be applied to a pointer. If you have an instance you must use . operator to access the members.

Please see: operators.

Finally a similar question you should read.

like image 95
Szabolcs Dombi Avatar answered Oct 24 '22 08:10

Szabolcs Dombi


The "arrow" operator -> is used to dereference pointers to objects to get their members. So if you have a pointer an object in the variable ui and the object has a member pushButton then you can use ui->pushButton to access the pushButton member. If the pushButton member in turn is a pointer to an object then you use -> again to access its members, like ui->pushButton->setText("Hello").

Using the "arrow" operator is basically just syntactic sugar for the dereference (unary *) and dot (.) member access operator.

So the statement

ui->pushButton->setText("Hello");

could also be written as

(*(*ui).pushButton).setText("Hello");
like image 43
Some programmer dude Avatar answered Oct 24 '22 08:10

Some programmer dude