PDA

View Full Version : function()->function() or function().function() notation



pierre58
13th September 2010, 19:06
While learning qt through the book : C++ GUI Programming with qt4, I've encounted this notation quite a few times : function()->function() or function().function().

Here is a common example from : http://doc.qt.nokia.com/4.6/qmainwindow.html (Creating Menus):


void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(newAct);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);


Usually, in C++, I encounter Classes containing attributes and methods, but when I look at this notation, I see a function containing a function.
I could guess that in this example the menubar() function returns a pointer to a QMenuBar which contains a addMenu() function returning a QMenu, but where is the QMenuBar object coming from? It does not seem to be declared as an attribute of QMainWindow.

How am I supposed interpret this notation ?
Does this notation have a name, if yes what is it ?

tbscope
13th September 2010, 19:21
You almost have it :-)


I could guess that in this example the menubar() function returns a pointer to a QMenuBar
To a QMenuBar object to be more specific.


but where is the QMenuBar object coming from? It does not seem to be declared as an attribute of QMainWindow.
Not all the class child objects or functions are publicly available. The menu bar for example is a private object inside the main window. You use access functions to reach them.

The menuBar() function returns the menu bar object.


class MyClass
{
public:
MyObject *getMyObject() const;

private:
MyObject *theObject;
};

MyObject *MyClass::getMyObject() const
{
return theObject;
}

...

MyClass *myclass = new MyClass(...);
MyObject *theObjectFromMyClass = myclass->getMyObject();

Kyle Arseneault
13th September 2010, 21:03
Pierre,
funct1()->funct2()
The way this works is similar to this from your example:


QMenuBar* temp;
QMenu* fileMenu;
temp = menuBar();
fileMenu = temp->addMenu(tr("&File"));

By calling implementing your code this way you can ensure that menuBar() returns a valid value.
Using funct1()->funct2() is unsafe because funct1() could return null causing a crash.
Hope this helps.
Kyle Arseneault
You I Labs (http://bit.ly/9DRRwd)