Share data between two classes.
-
How and what do i include in the header files so that i can get data from mainwindow.cpp into employee.cpp and vice versa.
I want both the classes to share each others data , even the .ui file.
It is working fine when i include one class in another , but it does not work when i include both in each other.I searched and i got that i have to do a forward declaration.
But i don't understand how . Its really frustrating . Please help.mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "employeeinfo.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); protected: private slots: private: Ui::MainWindow *ui; employeeinfo *emp; }; #endif // MAINWINDOW_H
employeeinfo.h
#ifndef EMPLOYEEINFO_H #define EMPLOYEEINFO_H #include <QMainWindow> namespace Ui { class employeeinfo; } class employeeinfo : public QMainWindow { Q_OBJECT public: explicit employeeinfo(QWidget *parent = 0); ~employeeinfo(); private slots: private: Ui::employeeinfo *ui; }; #endif // EMPLOYEEINFO_H
-
Hi,
What exactly do you want to share ? For what purpose ?
-
@ronyNS said:
want to share username variable from main window.
You have several options besides coupling two classes, which is generally considered a bad idea.
You can use setters and getters, pass the value in the constructor, or signals and slots. Signals and slots ties in quite well with event driven programming.
Mike
-
I just gave you 1 example about the username.
There are many things that i want in employeeinfo.h , i even want the text field present in the mainwindow.ui.
Is there a way where i can include mainwindow.h in employeeinfo.h and get the data i need from mainwindow.
Thank you. -
Just adding a header file here won't help much and you are doing it the wrong way around.
Why should your EmployeeInfo class know anything from MainWindow ? That's only going to create a tight coupling and the time you'll want to change MainWindow for something else, you'll also have to change EmployeeInfo.
If you are going to show EmployeeInfo from MainWindow, add setters to EmployeeInfo that you'll use to update its content before showing it like already suggested by @mjsurette or use properties/signals and slots.