Qub1
Qub1

Reputation: 1244

Use functions from another class which includes this class

Alright, I'm completely lost here.

I have two classes, mainwindow.cpp and settings.cpp. Both use functions from the other. So I've tried to make each include the other, but this resulted in an include loop. So I had to use forward declarations. However these resulted in the error: forward declaration of 'class Settings'.

This is my code now:

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

class Settings;

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow {
    Q_OBJECT

    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
        void someFunction();

    private:
        Ui::MainWindow *ui;
        Settings *settings;
};

#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);

        QTreeWidgetItem* status;

        QString setting = settings->getSomeSetting();
    }

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

    void someFunction() {
        // DO STUFF
    }

settings.h:

#ifndef SETTINGS_H
#define SETTINGS_H

class MainWindow;

class Settings : public QSettings {
    public:
        Settings();
        QString getSomeSetting();
    private:
        MainWindow *mainwindow;
};

#endif // SETTINGS_H

settings.cpp:

#include "settings.h"

Settings::Settings() : QSettings(qApp->applicationDirPath() + "/settings.ini", QSettings::IniFormat) {
}

QString Settings::getSomeSetting() {
    mainwindow->someFunction();
    return "somesetting";
}

So could anyone give some guidance on how to do this? Thanks in advance!

Upvotes: 0

Views: 76

Answers (2)

Silicomancer
Silicomancer

Reputation: 9166

You need #include "settings.h" in mainwindow.cpp and #include "mainwindow.h" in settings.cpp.

Read about the difference of declration and definition.

Upvotes: 1

Floris Velleman
Floris Velleman

Reputation: 4888

You are missing an include and have a forward declaration that is not needed. If you add an include to the mainwindow.h (#include "settings.h") and forward declare the mainwindow class in your settings header this should work just fine.

Upvotes: 1

Related Questions