Avoiding circular dependancy with C++ in MVC design - c++

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.

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.

Related

Header file - Inheritance c++

My experience in c++ is very limited, so I excuse if my question is dumb or elementary. Here goes:
When doing larger project in a language like c++, and you possibly have a very big line of inheritance, is it normal practice to include every single derived class in the.. main file, let's say.
Is there some way to circumvent this, or am I missing something banal?
Thank you.
For a C++ program to use a C++ class, it requires the declaration. If the class inherits from base classes, then those declarations are required to process that class declaration. This applies recursively: the entire inheritance tree of the class is required.
If the inheritance graph is so deep and broad (perhaps due to multiple inheritance) that the project decides it is unacceptable, then it has to be restructured. Classes might be able to use aggregation instead of inheritance. So that is to say, instead of:
#include <widget.h>
class foo : public widget { ... };
it may be possible to have;
class widget; // "forward" declaration only; no #include needed
class foo { widget *pwidget; ...}
Now, only the file which implements foo needs the full declaration of widget; the clients of foo which are including "foo.h" don't need it.
But now foo is not a-kind-of widget any longer, which has implications on the code organization. foo still has the widget parts by way of creating an object and holding it. If widget conforms to some abstract interface for widgets, foo may be able to implement that, and delegate to the contained widget.
Another tool in minimizing dependencies is dependency inversion.

C++ include header file

So, I'm having a problem where:
class A needs to know about class B, class B needs to know about C, and class C needs to know about A.
It's essentially a circle, so I get definition errors. I tried forward declaration, but whatever's on top, doesn't know about what else goes on at the bottom.
How would I go about a situation like this?
Thanks
David
Assuming this is something simple, the comment above by Adam Mihalcin is correct in that the similar question answers it. But I'll code it out anyways.
Assuming you have this (method definitions don't matter) :
class A
{
B* ptrB;
}
class B
{
C* ptrC;
}
class C
{
A* ptrA;
}
Then you can, as Adam linked to, just forward-delcare all 3 of them like this:
class A;
class B;
class C;
And put that block above all 3 of them. The important thing here though is that this is when there are pointers to the other classes, not composition where they're a part of the class. You can use forward-declaration to allow things to compile correctly when dealing with pointers, but not with other data types. So if there was this:
class D
{
B myB;
}
With everything else the same as above, you'd need to have the "real" definition for B above the "real" definition for D. But the rest could be the same. Forward declaration only "works" for pointers.
You MUST break your dependency loop somewhere with a pointer though. If there's never a pointer, then the data structure is "infinite" and thus doesn't work. That's because in my example, a D always contains a B. But what if an A always contained a B, and a B always contained a C, and a C always contained an A? Well that final A needs another B, which needs another C, which... I hope you get the idea. But with pointers, you can loop it. With composition (not pointers) it can't loop around.
If the classes are tightly coupled, then you can do with
Declare the classes with no method implementations, possibly using forward declarations, then implement the methods (possibly in an implementation file).
Otherwise, you can
Factor out the more abstract interface(s) sufficient for the classes to work without knowing full details about each other.
But most probably you have a design level error, and if so, just fix that.
What you can do is forward declare class A in in the header file for class C, then you in the .cpp file, you include the header for class A.
For a reference on how to forward declare class A, take a look at this reference - Forward declarations in C++
most probably, u've just got an design level error.
However, if u have to do this, for example , just try to utilize forward-declare by declaring an empty class A,B without presenting any detail implementation in C's header file. then include A and B's header in C's implementation file when u need to use them.
Remember, u can only use pointer in the declaration of class C.
In your header files use next construction:
#ifndef MYCLASS_HPP__20120410__0747
#define MYCLASS_HPP__20120410__0747
// Your definions of class, struct, etc...
#endif//
And all included file (except self Myclass.hpp) should be in class-header file Myclass.hpp. He must be included in Myclass.cpp file.

Wrapper design pattern

Say I have a class:
class B;
class A{
public:
A();
virtual B foo();
}
defined in a 3rd party component. I want to wrap classes A and B, resulting myA and myB.
Now, I shouldn't be able to access class A and class B from the outside, but rather have the same functionality for myA and myB. foo() could be called from the 3rd party module.
I would prefer to do this using inheritence, not encapsulation.
So there are 2 problems:
Calling a->myFoo() (need to rename methods because of same signature and different return type) should call A::foo() if a is of type myA.
Calling a->myFoo() should call myA2::myFoo() if a is of type class myA2::myA.
Any suggestions on how to do this elegantly? I came up with some solutions but I prefer a fresh view on the whole thing.
EDIT:
Just a theoretical question. I don't actually need to do this, just thinking of ways it can be achieved.
EDIT2:
myA2 is a class that extends myA. Before the pattern, it would have been called A2 (a class that extended the class A from the 3rd party module).
I don't understand why you prefer to do this with inheritance instead of encapsulation. Generally speaking, extending the class you're wrapping is the "wrong" way to implement the wrapper pattern, especially since you generally want to redefine the interface in the process. In class myA, you'll have a field of type A that contains an instance of class A, which methods in myA can call upon as needed. Unless I've misunderstood what you want to accomplish, this is the most elegant way to accomplish what you want.
You should be able to declare the function names/parameters similarly. Check out:
strange-inheritance section: [23.9] What's the meaning of, Warning: Derived::f(char) hides Base::f(double)? on the 3rd code block.
It also shows the syntax for calling base methods.

Polymorphism ambiguities, can we resolve them with a "default" base to use

I need a layer of abstraction involving QWidget that can be QGLWidget, and I wonder if there is a way to say to the compiler, "Any time you have a doubt (ambiguities) try to use the default base I give you", of course if there is ambiguities it can't resolve with the default choice it prompts errors just like it does. My aim is not have to explicitly solve each of ambiguities one by one since I will always re-direct them to the same class.
Quick setup,
#Qt inheritance (very roughly...)
class QWidget {};
class QGLWidget : public QWidget {};
#my side
class MyAbstract : public QWidget {}; //used by a factory
class MyClass1 : public MyAbstract {};
class MyClass2 : public MyAbstract, public QGLWidget{};
I'am aware compiler can't determine by its-self witch duplicated methods to use for the MyClass2 class, since QGLwidget inherits and re-implement most of the QWidget, but can I tell to the complier to use QGLWidget first since I know that's what I want ?
Qt is just an example here.
I personally doubt that this kind of automatic disambiguation is feasible in C++ at the language level.
What is possible is, case-by-case, disambiguate by explicitly giving the class whose method should be executed, like this:
QGLWidget::ambiguous_method(...
This is not what you are asking for, I know, and I am sure you already know about it. I am saying just for completeness.
On another hand, I am not sure that this kind of automatic disambiguation would be desirable or simply helpful, because the main point about multiple inheritance being "delicate" is the replication of data inside of the derived class. If you had automatic disambiguation, you would end up using sometimes (when there is no ambiguity) the partial object corresponding to a base class, and in other cases the partial object corresponding to the other base class (because of automatic disambiguation) and you would get a mosaic of things that would not make any sense, i.e. a corrupt object...
Finally, I think that this kind of automatic disambiguation would be infeasible in case you have more complex inheritance diagrams, like, following your example:
class Nasty : QGLWidget {};
class Very_nasty : Nasty, MyClass2 {};
There would be no possibility of automatic disambiguation. Indeed, say that the classes you provided form a library and that you decided, when building the library, to use MyClass2::QGLWidget as a base for disambiguation.
Now, I take your library and define two more classes like the ones I gave. Very_nasty inherits QGLWidget from Nasty and from Class2; each one has got a QGWidget inside, and overall I have 3 of them (because Class2 already inherited it twice).
Now suppose that for me, a base class for disambiguation should be Very_Nasty::Nasty::QGLWidget, given the semantics of my class. If you say that automatic disambiguation is a way to resolve ambiguities with multiple inheritance, I should be able to specify it with each case of multiple inheritance.
What would happen if I call through Very_nasty a method inherited from MyClass2?
What would happen if I call through Very_nasty a method inherited from Nasty?
They would take two different disambiguation paths. Clash.
Good answer: don't model anything as inheritance until it's absolutely necessary.
Exact answer: use virtual base class.

OOP vs macro problem

I came across this problem via a colleague today. He had a design for a front end system which goes like this:
class LWindow
{
//Interface for common methods to Windows
};
class LListBox : public LWindow
{
//Do not override methods in LWindow.
//Interface for List specific stuff
}
class LComboBox : public LWindow{} //So on
The Window system should work on multiple platforms. Suppose for the moment we target Windows and Linux. For Windows we have an implementation for the interface in LWindow. And we have multiple implementations for all the LListBoxes, LComboBoxes, etc. My reaction was to pass an LWindow*(Implementation object) to the base LWindow class so it can do this:
void LWindow::Move(int x, int y)
{
p_Impl->Move(x, y); //Impl is an LWindow*
}
And, do the same thing for implementation of LListBox and so on
The solution originally given was much different. It boiled down to this:
#define WindowsCommonImpl {//Set of overrides for LWindow methods}
class WinListBox : public LListBox
{
WindowsCommonImpl //The overrides for methods in LWindow will get pasted here.
//LListBox overrides
}
//So on
Now, having read all about macros being evil and good design practices, I immediately was against this scheme. After all, it is code duplication in disguise. But I couldn't convince my colleague of that. And I was surprised that that was the case. So, I pose this question to you. What are the possible problems of the latter method? I'd like practical answers please. I need to convince someone who is very practical (and used to doing this sort of stuff. He mentioned that there's lots of macros in MFC!) that this is bad (and myself). Not teach him aesthetics. Further, is there anything wrong with what I proposed? If so, how do I improve it? Thanks.
EDIT: Please give me some reasons so I can feel good about myself supporting oop :(
Going for bounty. Please ask if you need any clarifications. I want to know arguments for and vs OOP against the macro :)
Your colleague is probably thinking of the MFC message map macros; these are used in important-looking places in every MFC derived class, so I can see where your colleague is coming from. However these are not for implementing interfaces, but rather for details with interacting with the rest of the Windows OS.
Specifically, these macros implement part of Windows' message pump system, where "messages" representing requests for MFC classes to do stuff gets directed to the correct handler functions (e.g. mapping the messages to the handlers). If you have access to visual studio, you'll see that these macros wrap the message map entries in a somewhat-complicated array of structs (that the calling OS code knows how to read), and provide functions to access this map.
As MFC users, the macro system makes this look clean to us. But this works mostly because underlying Windows API is well-specified and won't change much, and most of the macro code is generated by the IDE to avoid typos. If you need to implement something that involves messy declarations then macros might make sense, but so far this doesn't seem to be the case.
Practical concerns that your colleague may be interested in:
duplicated macro calls. Looks like you're going to need to copy the line "WindowsCommonImpl" into each class declaration - assuming the macro expands to some inline functions. If they're only declarations and the implementations go in a separate macro, you'll need to do this in every .cpp file too - and change the class name passed into the macro every time.
longer recompile time. For your solution, if you change something in the LWindow implementation, you probably only need to recompile LWindow.cpp. If you change something in the macro, everything that includes the macro header file needs to be recompiled, which is probably your whole project.
harder to debug. If the error has to do with the logic within the macro, the debugger will probably break to the caller, where you don't see the error right away. You may not even think to check the macro definition because you thought you knew exactly what it did.
So basically your LWindow solution is a better solution, to minimize headaches down the road.
Does'nt answer your question directly may be, but can't help from telling you to Read up on the Bridge Design pattern in GOF. It's meant exactly for that.
Decouple an abstraction from its
implementation so that the two can
vary independently.
From what I can understand, you are already on the right path, other than the MACRO stuff.
My reaction was to pass an
LWindow*(Implementation object) to the
base LWindow class so it can do this:
LListBox and LComboBox should receive an instance of WindowsCommonImpl.
In the first solution, inheritance is used so that LListBox and LComboBox can use some common methods. However, inheritance is not meant for this.
I would agree with you. Solution with WindowsCommonImpl macro is really bad. It is error-prone, hard to extend and very hard to debug. MFC is a good example of how you should not design your windows library. If it looks like MFC, you are really on a wrong way.
So, your solution obviously better than macro-based one. Anyway, I wouldn't agree it is good enough. The most significant drawback to me is that you mix interface and implementation. Most practical value of separating interface and implementation is ability to easily write mock objects for testing purposes.
Anyway, it seems the problem you are trying to solve is how to combine interface inheritance with implementation inheritance in C++. I would suggest using template class for window implementation.
// Window interface
class LWindow
{
};
// ListBox interface (inherits Window interface)
class LListBox : public LWindow
{
};
// Window implementation template
template<class Interface>
class WindowImpl : public Interface
{
};
// Window implementation
typedef WindowImpl<LWindow> Window;
// ListBox implementation
// (inherits both Window implementation and Window interface)
class ListBox : public WindowImpl<LListBox>
{
};
As I remember WTL windows library is based on the similar pattern of combining interfaces and implementations. I hope it helps.
Oh man this is confusing.
OK, so L*** is a hierarchy of interfaces, that's fine. Now what are you using the p_Impl for, if you have an interface, why would you include implementation in it?
The macro stuff is of course ugly, plus it's usually impossible to do. The whole point is that you will have different implementations, if you don't, then why create several classes in the first place?
OP seems confused. Here' what to do, it is very complex but it works.
Rule 1: Design the abstractions. If you have an "is-A" relation you must use public virtual inheritance.
struct Window { .. };
struct ListBox : virtual Window { .. };
Rule 2: Make implementations, if you're implementing an abstraction you must use virtual inheritance. You are free to use inheritance to save on duplication.
class WindowImpl : virtual Window { .. };
class BasicListBoxImpl : virtual ListBox, public WindowImpl { .. };
class FancyListBoxImpl : public BasicListBoxImpl { };
Therefore you should read "virtual" to mean "isa" and other inheritance is just saving on rewriting methods.
Rule3: Try to make sure there is only one useful function in a concrete type: the constructor. This is sometimes hard, you may need some default and some set methods to fiddle things. Once the object is set up cast away the implementation. Ideally you'd do this on construction:
ListBox *p = new FancyListBoxImpl (.....);
Notes: you are not going to call any abstract methods directly on or in an implementation so private inheritance of abstract base is just fine. Your task is exclusively to define these methods, not to use them: that's for the clients of the abstractions only. Implementations of virtual methods from the bases also might just as well be private for the same reason. Inheritance for reuse will probably be public since you might want to use these methods in the derived class or from outside of it after construction to configure your object before casting away the implementation details.
Rule 4: There is a standard implementation for many abstractions, known as delegation which is one you were talking about:
struct Abstract { virtual void method()=0; };
struct AbstractImpl_Delegate: virtual Abstract {
Abstract *p;
AbstractImpl_Delegate (Abstract *q) : p(q) {}
void method () { p->method(); }
};
This is a cute implementation since it doesn't require you to know anything about the abstraction or how to implement it... :)
I found that
Using
the preprocessor #define directive to
define constants is not as precise.
[src]
Macros are apparently not as precise, I did not even know that...
The classic hidden dangers of the preprocessor like:
#define PI_PLUS_ONE (3.14 + 1)`
By doing so, you avoid the possibility
that an order of operations issue will
destroy the meaning of your constant:
x = PI_PLUS_ONE * 5;`
Without
parentheses, the above would be
converted to
x = 3.14 + 1 * 5;
[src]