Reputation: 1234
I'm trying to implement the MVC design pattern in a Qt app I'm working on and would like to put menu bar in its own class derived from QMenuBar (I'm calling it Menu) while the window itself is another class derived from QMainWindow (I'm calling it MainWindow). In order to attach the menu bar to the main window, I need to pass a pointer to MainWindow on to the Menu class. Unfortunately this makes Menu dependent on MainWindow, which I would like to avoid.
I'm somewhat of a C++ noob and even more so with respect to MVC design so, would anyone know of an elegant solution to this problem? A little googling turned up that forward declaration may solve my problem, but I'm wondering if there might be a simpler way. I can provide some example code if need be, but the essence of the problem is I just want to pass a reference to ClassA to ClassB.
ClassA.cpp
ClassA() : ClassC
{
}
ClassB.cpp
ClassB(ClassA *parent) : ClassD
{
ClassA *my_parent = parent;
}
Is forward declaration the elegant solution to this kind of thing, or is there maybe a better way?
EDIT:
For anyone else having a similar problem, forward declaration most likely the answer for simple cases. This article by Disch at cpluplus.com proved helpful for me:
http://www.cplusplus.com/forum/articles/10627/
Here is the advice I found most helpful:
There are two basic kinds of dependencies you need to be aware of: 1) stuff that can be forward declared 2) stuff that needs to be #included If, for example, class A uses class B, then class B is one of class A's dependencies. Whether it can be forward declared or needs to be included depends on how B is used within A: - do nothing if: A makes no references at all to B - do nothing if: The only reference to B is in a friend declaration - forward declare B if: A contains a B pointer or reference: B* myb; - forward declare B if: one or more functions has a B object/pointer/reference as a parementer, or as a return type: B MyFunction(B myb); - #include "b.h" if: B is a parent class of A - #include "b.h" if: A contains a B object: B myb; You want to do the least drastic option possible. Do nothing if you can, but if you can't, forward declare if you can. But if it's necessary, then #include the other header.
Upvotes: 1
Views: 172
Reputation: 7448
Direct inclusion in the headers are only required if: the member of a class is not a pointer (don't do it with not trivial classes) or if you have to subclass the included class.
In all other cases use forward declaration. It's not a 'guru-feature', it's the standard way of solving unnecessary dependences.
P.S.: If you asking questions like this, I would suggest reading some introduction-literature on C++ and Qt. I'm not sure, if sub-classing such Qt classes as QMenuBar and QMainWindow with your current level of experience is the right way. Read QtCreator documentation. Check QML/QtQuick.
Upvotes: 2