PDA

View Full Version : How can I make an object global?



Awareness
17th March 2010, 23:39
I want to have global objects,so that I can use them inside seperate functions,how can I make them?For example,when I write

QLabel *label1=new QLabel;

under "#include sections",over "functions sections",it gives an error while starting debugging although it doesn't give any error while compiling.

Archimedes
17th March 2010, 23:54
What do you mean global objects? If you include the file where the object is defined, you can use it. Or maybe you mean declare something on file foo.h and use it on file foo2.h?
Also what errors the debugger reported?

Awareness
18th March 2010, 00:00
Thanks for your answer.

For example,I want to create a QLabel object(or is it called widget?) called Label1 which can be used(accessed to) from both main function and another function which I created.How can I do this?

Debugger error:"This application has requested the Runtime to terminate it in an unusual way.Please contact the application's support team for more information."

Archimedes
18th March 2010, 00:31
Read this global variables (http://www.learncpp.com/cpp-tutorial/42-global-variables/).

Awareness
18th March 2010, 00:41
Thanks for your answer.I was thinking a Label is not a variable?

Archimedes
18th March 2010, 02:08
You should really read the whole C++ tutorial in the site I gave you, not just the part about global variables.

Awareness
18th March 2010, 21:00
I have read it,that page doesn't recommend using global variables.But I need to access objects inside functions,how can I do it?

wysota
18th March 2010, 21:15
It would be best if you used the Singleton design pattern.

mengedej
19th March 2010, 11:01
Create a interface in the class owning the label that lets you modify it in the way you want.
e.g: updateLabel(QString textForLabel)
{
//code to modify Label
}

then let your other class access the label through this function?

JD2000
19th March 2010, 13:55
Declare them outside of main() or put them in a header file
but it is best not to use them where they can be avoided.


#include <QtGui/QApplication>
#include "mainwindow.h"
#include "myglobals.h"

// globals here
int aInteger;


int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}

Awareness
27th March 2010, 05:32
(Sorry for my late reply)

Thanks for your answers.

JD2000,I tried writing into "globals here section" but it gives an error.It works when I use it in a header file though.