1

I have following code snippet. I want to access my stack from another class. (This stack is filled with QWidgets which i need in some other classes). But i didn't even get as far as initializing my static variable in my mainwindow constructor. The error message is : "qualified-id in declaration before '=' token"

/*mainwindow.h*/
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0); //Konstruktor
    ~MainWindow(); //Destruktor

    //static QStack<QWidget*> *widgetStack;
    //static QStack<QWidget*> getWidgetStack();
    static QStack<QWidget*> *widgetStack;


private:
    Ui::MainWindow *ui;

/*mainwindow.cpp*/
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent), ui(new Ui::MainWindow)
{
    /*ui->setupUi(this);
     QStack<QWidget*> *MainWindow::widgetStack = new QStack<QWidget*>();

}

/*A method in another class*/
void Support::on_Taster_Power_clicked()
{
    MainWindow.widgetStack->pop();
}

I tried really a lot but nothing worked out for me. please help. thanks in advance

m.s.
  • 16,063
  • 7
  • 53
  • 88
Greenfish
  • 358
  • 2
  • 5
  • 19
  • 2
    Duplicate: http://stackoverflow.com/questions/7033649/c-class-with-static-pointer?rq=1 , you need to initialize it outside your class in one cpp file. – coyotte508 Oct 15 '15 at 13:00
  • 1
    any reason why the stack AND the widgets themselves are pointers? – David Haim Oct 15 '15 at 13:02
  • 1
    There's a lot of things that scare me in this design :/ – undu Oct 15 '15 at 13:05
  • thanks for your help. sorry, i am new to c++, came from java. i've read something about pointers and the differences between a heap and a stack but i don't understand why i should have both as pointers. would it be better to only have the stack as pointers and the widgets not? – Greenfish Oct 15 '15 at 13:36
  • It would be best if both are "regular" types and not pointers, AKA `static QStack widgetStack;` – David Haim Oct 15 '15 at 18:58

2 Answers2

1
/*mainwindow.cpp*/

QStack<QWidget*> *MainWindow::widgetStack = new QStack<QWidget*>();

MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent), ui(new Ui::MainWindow)
{
    /*ui->setupUi(this); */
}
coyotte508
  • 9,175
  • 6
  • 44
  • 63
0

The order of initialization of non-local static objects defined in different translation units is not specified by the standard. This is error prone...

Static objects inside functions are known as local static objects (because they’re local to a function), and the other kinds of static objects are known as non-local static objects.

I strongly recommends you to use this way:

static const QStack<QWidget*>& getWidgetStack() {
  static QStack<QWidget*> widgetStack = QStack<QWidget*>();
  return widgetStack;
}

static QStack<QWidget*>* getMutableWidgetStack() {
  const_cast<QStack<QWidget*>*>(&getWidgetStack());
}