Hello. I'm quite new to programming and for a few days I was trying to figure out how could I use an object I created in, for instance, main.cpp in other module, like mainwindow.cpp. Here's my code:
main.cpp:
Thanks. It works. But my Teacher told me that I shouldn't use global variables. Right now I am stuck in other place. My code compiles, but I get segfault. I assume it is because *rental and *db stop existing after mainwindow.cpp bit of code. How do I make them last longer?
mainwindow.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
MainWindow::MainWindow(FotoRental *rental, DB* db) :
QMainWindow(),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
Fotos fotos = rental->getAllFotos();
for (int i = 0; i < fotos.size(); i++) {
...
}
Customers customers = rental->getCustomers();
for (int i = 0; i < customers.size(); i++) {
...
}
}
main.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13
int main(int argc, char *argv[])
{
DB* db = new DB("c:/cpp/rental.txt");
FotoRental* rental = new FotoRental;
*rental = db->loadFotoRental();
QApplication a(argc, argv);
MainWindow w(rental,db);
w.show();
return a.exec();
}
mainwindow.h:
1 2 3 4 5 6 7 8 9 10
class MainWindow : public QMainWindow
{
Q_OBJECT
DB* db;
FotoRental* rental;
public:
explicit MainWindow(FotoRental* rental, DB* db);
~MainWindow();
...
Ahh, good teacher! You have to initialize MainWindow::rental in the constructor otherwise it will be uninitialized when you try to use it in other member functions.