Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

Why do I have to re-declare the class static variables in both .cpp and .h files?

In QT, I have a class called MainWindow. I have a variable called plotGrpahics declared as static in my header MainWindow.h file: class MainWindow : public QMainWindow { static QGraphicsScene * plotGrpahics; } However the variable is not seen in my MainWindow.cpp file until I re-declare it there like this: QGraphicsScene * MainWindow::plotGrpahics; The variable is then initialized in the run-time inside the MainWindow constructor: plotGrpahics = new QGraphicsScene(); Now this actually works perfectly, but I don't know why I have to declare it twice!! 1- Of course the .h is included in the .cpp. 2- I checked that they are both the same variable in runtime, and when I delete either the .h definition or the .cpp definition, the code does not compile! 3- It is also not an access modifier issue, this happens with both public and private static variables. 4- As you can see, it not an initialization issue.

user-image
Question ajoutée par Ahmed Zahran , Senior Software Developer , Oracle
Date de publication: 2013/04/29
Daniel Marx
par Daniel Marx , Software Developer , Check24

Hi, afaik class definitions, in this case the header files, are just templates and no memory will be allocated.
Static variables on the other side need memory assigned as this won't be handled by the class instance (cause static variables aren't bound to instances).
That's why statics in header files have to be redeclared withing the .cpp file, outside the class.
Hope that helped a bit but it's one of those c++ issues that every developer bumbs into someday.
And if I'm wrong please feel free to correct me, Daniel

Ahmed Zahran
par Ahmed Zahran , Senior Software Developer , Oracle

I believe you are completely right, Daniel., Thanks a lot! There is a point I need to clarify to make this question useful to others.
I did not consider memory allocation problems, because my static variable was a pointer to an object.
I thought since it (the object) was already not allocated until I use the "new" keyword in run-time, I have no problem.
But my real problem was the pointer itself! The pointer is itself a variable, it needed an allocated slot in memory to hold the address of the object it was pointing to, even if the object is not initialized yet...

More Questions Like This