PDA

View Full Version : Static variable problem



mvbhavsar
2nd January 2015, 06:49
Hi,

I am having problem while using static variables. I want to retain screen dimensions as static variable values and use it across many classes. Hence I have following case.

Utilities class is common class having many general methods.

utilities.h
===========


#ifndef UTILITIES_H
#define UTILITIES_H

#include <QtWidgets>
class Utilities{
static int ScreenWidth;
public:
explicit Utilities();

int screenDimension(){
return ScreenWidth;
}
void setScreenDimension(int pr){
ScreenWidth = pr;
}
};
#endif // UTILITIES_H



MainWindow class is a class which will have main window and will assign value to ScreenWidth variable of Utilities class.

mainwindow.h
============


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtWidgets>
#include "utilities.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

protected:
void resizeEvent(QResizeEvent *e);

private:
Ui::MainWindow *ui;
Utilities ut;
};

#endif // MAINWINDOW_H


mainwindow.cpp
==============



#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *e)
{
QSize graphicsViewSize = ui->graphicsView->size();
ut.setScreenDimension(graphicsViewSize.width);
}


When I compile this it gives me an error as below

H:\Sample\mainwindow.cpp:-1: error: undefined reference to `Utilities::ScreenWidth'



Thanks

Manish

anda_skoa
2nd January 2015, 12:19
Looks like you forgot to define the static field.

One compilation unit (.cpp file) of your application needs to "hold the memory" location for the static variable.



int Utilities::ScreenWidth = 0;


Btw, are you sure you want a static member variable and non-static accessors?

Cheers,
_

mvbhavsar
2nd January 2015, 13:25
Thanks. Yes it has solved the problem. By the way what is the risk in this approach? Why i should not use static variables accessed by non static accessors.




Manish

anda_skoa
2nd January 2015, 14:47
No risk, but why do you want to create an instance of a class that does not contain instance data?

Cheers,
_