Class pointers in classes, recursion and typecasting


#1

i have a question that might be more related to C++ then Juce itself.
(i’m sorry if the answer to this is yet again obvoius but all my programming “skills” are my own experience i nver took any classes and have been working mostly with ANSI C and less with OO programming). Here goes.

in the audio plugin framework you declare a class that’s the base class, than another one that’s the editor, the editor has the pointer to the filter, but what if the filter would like a pointer to the editor. When the createEdtitor() is called in the base

 return new DemoEditorComponent (this);

gets called, but what if i wanted a pointer to the editor stored in the Base class. What i mean is the error i always get myslef into, recursuve inclusions. I would like the Base to reference the editor as a member pointer and vice-versa, but that gives the obvious error of doing

#include "Editor.h" in Base.h
and
#include "Base.h" in Editor.h

and that’s an Error for the compiler and fully understand it. But what’s the way around it. The one i found is setting a pointer in my Base class defined as

Component *_editorPtr;

and than typecast it (include the Editor.h in the Base.cpp like it’s done in the demo) like that

Editor *editorPtr = (Editor *)_editorPtr;

but i don’t know if this is not some kind of a very bad thing to do and my computer wont explode after doing too many of those. Also i can do this per-method basis and i am not sure how efficient that is when too many typecasts occur in my code.

many thanks for any answers.


#2

Don’t include “Editor.h” in “Base.h”

instead add the line:

class DemoEditorComponent;

then you can do:

DemoEditorComponent* _editorPtr;

then, in your cpp file, include “editor.h”


#3

To get around the recursive thing, you have to forward-declare a class with the line “class MyClass;”, and then include it later (in the cpp file). There must be lots of c++ tutorials out there that explain this much better than me…

And it’s perfectly ok to cast the editor, as long as you always know what it will be. It’s slightly better to dynamic_cast it, and check that the result is non-zero. Neither way should take a significant amount of time.


#4

forward declaration and google did the trick thanx

[http://www-subatech.in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml]


#5